JS Polymorphism

Polymorphism is a core concept in object-oriented programming that allows methods to do different things based on the object it is acting upon. In JavaScript, polymorphism enables you to call the same method on different objects, where each object can respond in its own way.

Key Concepts

• Single Method, Multiple Forms: Polymorphism allows a single method to have different implementations depending on the object or the data passed to it.

• Dynamic Method Resolution: JavaScript's polymorphism is dynamic, meaning that the method to be executed is determined at runtime based on the object instance.

Types of Polymorphism

1. Method Overriding: A child class can provide a specific implementation of a method that is already defined in its parent class. This is an example of compile-time polymorphism in class-based languages, but in JavaScript, it's achieved using class inheritance and method overriding.

2. Method Overloading: JavaScript does not support method overloading in the traditional sense (like in Java or C++), where methods with the same name but different parameters are defined. However, polymorphism can be achieved through flexible methods that handle different types of arguments.

Examples:

1. Method Overriding

<script>
class Animal {
    speak() {
        console.log('Animal makes a sound');
    }
}

class Dog extends Animal {
    speak() {
        document.write('Dog barks');
    }
}

class Cat extends Animal {
    speak() {
        document.write('Cat meows');
    }
}

const myDog = new Dog();
const myCat = new Cat();

myDog.speak(); // Output: Dog barks
myCat.speak(); // Output: Cat meows
</script>

Flexible Method Implementation

<script>
function greet(person) {
    if (typeof person === 'string') {
        document.write(`Hello, ${person}!`);
    } else if (person instanceof Person) {
        document.write(`Hello, ${person.name}!`);
    } else {
        document.write('Hello, stranger!');
    }
}

class Person {
    constructor(name) {
        this.name = name;
    }
}

greet('Alice'); // Output: Hello, Alice!
greet(new Person('Bob')); // Output: Hello, Bob!
greet(123); // Output: Hello, stranger!
</script>

Advantages of Polymorphism

Flexibility: It allows for writing more flexible and reusable code. You can design methods that operate on different types of objects without knowing their specific classes.

Maintainability: By using polymorphism, you can change the behavior of methods in derived classes without modifying the code that uses the base class.