Javascript - Class Method Overriding

Introduction

The methods of the parent class can be shadowed with the same name on the parent class, inside the derived class.

The following code where fly() method from the parent class (Bus) is being overridden inside the derived class (SchoolBus):

Demo

class Bus { 
        constructor(capacity) { /*from  w ww  .j a va2 s .c  o  m*/
                this.capacity = capacity; 
        } 

        showCapacity() { 
                console.log(`Capacity of this bus: ${this.capacity}`); 
        } 

        fly() { 
                console.log("Engines on, and the bus will leave soon"); 
        } 
} 

class SchoolBus extends Bus { 
        fly() { 
                console.log("Engines on, and the bus is gone"); 
        } 

        load() { 
                console.log("Loading students"); 
        } 
} 
const phantom = new SchoolBus(2); 
phantom.fly(); // Engines on, and the bus is gone 
phantom.showCapacity();

Result

To access the parent class version of the method, use super.fly() as follows:

class SchoolBus extends Bus { 
        fly() { 
                super.fly(); 
                console.log("Engines on, and the bus is gone"); 
        } 
} 

This ensures that first, the parent class's method will be called every time the fly() method is called on the SchoolBus's instance.

Besides methods, you can override constructors, for example:

class Bus { 
        constructor(capacity, color) { 
                this.capacity = capacity; 
                this.color = color; 
        } 
} 

class SchoolBus extends Bus { 
        constructor(color) { 
            // This is 2-seater 
            super(2, color); 
        } 
} 

const phantom = new SchoolBus("grey"); 

console.log(phantom.capacity);       // 2