JavaScript Polymorphism

The polymorphism is a core concept of an object-oriented paradigm that provides a way to perform a single action in different forms. It provides an ability to call the same method on different JavaScript objects. As JavaScript is not a type-safe language, we can pass any type of data members with the methods.

Polymorphism Syntax


class ParentClass {
    display() {
        return "This is a method from the ParentClass.";
    }
}
            
class ChildClass extends ParentClass {
    display() {
        return "This is a method from the ChildClass.";
    }
}

Key Features of Polymorphism:

Example: Implementing Polymorphism

Example 1


class Animal {
    speak() {
        return "This animal makes a sound.";
    }
}
            
    class Dog extends Animal {
        speak() {
            return "The dog barks.";
        }
}
            
    class Cat extends Animal {
        speak() {
            return "The cat meows.";
        }
}
            
// Using the classes
const animals = [new Animal(), new Dog(), new Cat()];
animals.forEach(animal => console.log(animal.speak()));
            

Output

This animal makes a sound. The dog barks. The cat meows.

Example 2


class Shape {
    area() {
    return "Area is not defined for this shape.";
    }
}
            
class Rectangle extends Shape {
    constructor(width, height) {
        super();
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }             
}
            
class Circle extends Shape {
    constructor(radius) {
        super();
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius ** 2;
    }             
}
            
// Using the classes
const shapes = [new Shape(), new Rectangle(5, 10), new Circle(7)];
shapes.forEach(shape => console.log(shape.area()));
           
            

Output

This animal makes a sound.
The dog barks.
The cat meows.

Area is not defined for this shape.
50
153.93804002589985

Explanation of Code: