Skip to content

Instantly share code, notes, and snippets.

@hafizali05
Last active December 3, 2018 10:36
Show Gist options
  • Save hafizali05/fed3877bc467ff0adb505da66957b989 to your computer and use it in GitHub Desktop.
Save hafizali05/fed3877bc467ff0adb505da66957b989 to your computer and use it in GitHub Desktop.

Polymorphism

What is polymorphism?

* Poly= many, morphism=form or behaviour shifting.
* It’s a programming language’s ability to process the objects differently depending on their data type and class.
* Polymorphism in Object-Oriented Programming is the ability to create a variable, a function, or an object that has more than one form.
* E.g: Lets find out info on the Person who can be an employee

Why we need it ?

The primary usage of Polymorphism in Object-Oriented Programming is the ability of objects belonging to different types to respond to methods, fields, or property calls of the same name, each one according to an appropriate type-specific behaviour.

How can I achieve this polymorphic behavior in javascript?

class Person {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    showInfo() {
        return `I'm ${this._name}, aged ${this._age}.`;
    }
}

class Employee extends Person {
    constructor(name, age, sex) {
        super(name, age);
        this._sex = sex;
    }

    showInfo() {
        return `I'm a ${this._sex} named ${this._name}, aged ${this._age}.`;
    }
}

const alice = new Person("Alice", 20);
const bob = new Employee("Bob", 25, "male");

console.log(alice.showInfo());
console.log(bob.showInfo());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment