Polymorphism Using Classes in JavaScript

What is Polymorphism?

In programming languages and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types. - Wikipedia

In order to simplify its meaning, we can say:

Polymorphism is the ability of an object to override its default methods and properties which it inherited with other objects from its parent Object.

For example, all cars by default are expected to move on land. But how about cars that decide to move, but this time on air?

Now let's use Javascript classes to explain polymorphism.

class Vehicle{
    constructor(){
        this.noOfTyres = 4; 
    }
    ...
}

class Bicycle extends Vehicle{
    constructor(){
        super();
        this.sourceOfEnergy = "mechanical"
    }
    ...
}

class Car extends Vehicle{
   ...
}

const fordEscape = new Car();
const bughatti = new Bicycle();

console.log(fordEscape.sourceOfEnergy); //  fuel
console.log(bughatti.sourceOfEnergy);   // mechanical

from the code above:

class Vehicle{
    constructor(){
        this.sourceOfEnergy = "fuel";
    }
   ...
}

Here, Vehicle is a class we wish to create instances or objects from. We have set sourceOfEnergy as the default for any object to be created from this class. However, we can decide to override this default property (polymorphism) by using super() The magic super() method helps us achieve polymorphism when using classes for polymorphism.

Hence, from our main code above, we overrode the sourceOfEnergy of the Bicycle class but not that of Car. This means that by logging the properties of these instances we will have:

console.log(fordEscape.sourceOfEnergy); //  fuel
console.log(bughatti.sourceOfEnergy);   // mechanical

Thanks for your time.