OOP (Object-Oriented Programming) — Polymorphism
Polymorphism means 'many forms.' In OOP, it allows different classes to respond to the same method in their own way. For example, imagine you have a method called makeSound(). A dog class might implement it to bark, while a cat class might implement it to meow. This makes your code flexible and scalable because you can use the same method name for different types of behavior. Polymorphism is especially useful when working with large systems or when you need to extend your code in the future without rewriting everything.
class Animal {
makeSound() {
console.log('Some generic sound');
}
}
class Dog extends Animal {
makeSound() {
console.log('Woof!');
}
}
class Cat extends Animal {
makeSound() {
console.log('Meow!');
}
}
let animals = [new Dog(), new Cat()];
animals.forEach(a => a.makeSound());