Junior — Middle
Explain the concept of polymorphism in object-oriented programming.
sobes.tech AI
Answer from AI
Polymorphism is a principle of object-oriented programming that allows objects of different classes to respond to the same messages (method calls) in different ways. In simpler terms, the same method can behave differently depending on the object that calls it.
For example, you have a base class Animal with a method makeSound(). The subclasses Dog and Cat override this method to produce different sounds:
class Animal {
makeSound() {
console.log('Some sound');
}
}
class Dog extends Animal {
makeSound() {
console.log('Woof');
}
}
class Cat extends Animal {
makeSound() {
console.log('Meow');
}
}
const animals = [new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
// Outputs:
// Woof
// Meow
Thus, polymorphism allows writing more flexible and extensible code, where you can work with objects through a common interface without worrying about specific implementations.