How to use polymorphism with classes in JavaScript

What is polymorphism?

According to Wikipedia:

“…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.”

In other words, polymorphism is an object’s ability to override its default methods and properties that it inherited from its parent Object.

For example, all vehicles are expected to have a source of energy. But what about the different kinds of vehicles that use different sources?

Let’s use JavaScript classes to explain polymorphism. Consider the following Vehicle class.

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

Here, Vehicle is a parent class from which we wish to create instances or objects. We have set sourceOfEnergy = "fuel" as the default for any object to be created from this class.

However, we can decide to override this default propertypolymorphism by with the super() method, which refers to an object’s parent.

Below are two child classes of Vehicle: Bicycle and Car.

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

class Car extends Vehicle{
   ...
}

Here, we overrode the sourceOfEnergy for the Bicycle class but not that of Car.

This means that when we log the properties of these instances, we will have:

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

console.log(fordEscape.sourceOfEnergy); //  fuel
console.log(bughatti.sourceOfEnergy);   // mechanical
Attributions:
  1. undefined by undefined