Polymorphism
What is Polymorphism?
The word Polymorphism comes from Greek, meaning "many forms." In Object-Oriented Programming, polymorphism allows objects of different classes to be treated as objects of a common parent class. More importantly, it allows different classes to execute the same method name but perform different behaviors.
In simpler terms: You can call makeSound() on a group of different animals, and each animal will make its own unique sound, even though you called the exact same method on all of them.
Polymorphism in Action
Polymorphism relies heavily on Inheritance and Method Overriding. Let's look at an example:
class Shape {
draw() {
console.log("Drawing a generic shape.");
}
}
class Circle extends Shape {
draw() {
console.log("Drawing a Circle 🔴");
}
}
class Square extends Shape {
draw() {
console.log("Drawing a Square 🟦");
}
}
// An array holding different forms of Shapes
const shapes = [new Shape(), new Circle(), new Square()];
// Polymorphism in action!
shapes.forEach(shape => {
shape.draw();
});
Output:
Drawing a generic shape.
Drawing a Circle 🔴
Drawing a Square 🟦
Notice how we just called shape.draw() in the loop. We didn't need to check if the shape was a Circle or a Square. JavaScript automatically knew which specific draw() method to execute based on the actual object type.
Why is this useful?
Polymorphism makes your code incredibly flexible and easy to extend. If you later decide to add a Triangle class, you just write the class, give it a draw() method, and drop it into the array. You don't have to change the loop code at all!
💡 Himanshu's Tip:
Polymorphism removes the need for giant if/else or switch statements. Instead of checking if (type === 'circle') drawCircle(), you just let the object handle its own behavior!
Interview Questions
- Define Polymorphism in your own words.
- How do Inheritance and Method Overriding relate to Polymorphism?
- What is a primary benefit of using Polymorphism in your code structure?