Polymorphism
MediumIn plain terms
Polymorphism allows different types to be used through a common interface. You call the same method name (e.g. speak()) on different objects (Dog, Cat), and each type runs its own implementation. The caller does not need to know the concrete type—they just use the interface.
This makes code flexible: you can add new types (e.g. Bird) without changing the code that calls speak(). Polymorphism is often achieved by inheritance (override methods) or by implementing the same interface. It is a key benefit of OOP for writing extensible, maintainable code.
What you need to know
- •Same interface, different behavior
- •Method overriding
- •Extensibility without changing callers
Example
Code is language-agnostic in spirit; adapt the idea to your language:
function makeAnimalSpeak(animal) {
console.log(animal.speak()); // Same call, different behavior
}
makeAnimalSpeak(new Dog("Rex")); // Woof!
makeAnimalSpeak(new Cat("Whiskers")); // Meow!Why this matters
Polymorphism is central to extensible design. Interviewers ask how you would add new types without changing existing code—polymorphism (and Open/Closed) is the answer.
How it connects
Achieved via inheritance (override methods) or interfaces (different implementations). It makes Open/Closed and Liskov Substitution practical: you can add new subtypes and plug them in where the base type is expected.
Interview focus
Be ready to explain these; they come up often.
- ▸Definition: same interface, different behavior; "many forms."
- ▸Two forms: overriding (inheritance) and implementing interface.
- ▸Benefit: callers depend on abstraction; new types can be added without changing callers.
Learn more
Dive deeper with these resources: