Ploymorphism

The definition of polymorphism is actually heavily debated. But the idea is the ability to call the same method on the different objects and each object responding in different ways. The idea with a polymorphism in Object-Oriented Programming is that it has the ability to process objects differently depending on their data type or class because JavaScript is a dynamically typed language. It actually limits the amount of polymorphism that we can have but the idea is still the same. The ability to redefine methods for child classes in allowing us to reuse some of the functionalities but also customize methods to their own objects and classes and polymorphism is useful.

Inheritance vs polymorphism

  • Inheritance allows code reusability and Inheritance allows the already existing code to be reused again in a program.
  • polymorphism provides a mechanism to dynamically decide what form of a function to be invoked.

Polymorphism

class Person {
    constructor(name, country, language) {
        this.name = name;
        this.country = country;
        this.language = language;
    }
    speak() {
        return this.name + " can speak " + this.language;
    }
}

class American extends Person {
    constructor(name, country, language, location) {
        super(name, country, language);
        this.location = location;
    }
    speak() {
        console.log(super.speak())
        return "An American " + this.name + " can speak " + this.language;
    }

}

const tim = new American("tim", "USA", "english", "North");
console.log(tim.speak());

the same named speak() method or function is used in different class.

Leave a Reply

Your email address will not be published.

ANOTE.DEV