Polymorphism & Interfaces
Write flexible code that works against shared contracts so new implementations plug in without modifying existing logic.
What you'll learn
- Understand runtime polymorphism through method overriding
- Replace sprawling if/else or switch chains with polymorphic objects
- Program to an interface (contract) rather than a concrete class
Polymorphism literally means “many forms.” It lets callers invoke the same method name (such as area() or pay(amount)) on different object types, and each object executes its own specialized implementation.
Killing Long if / else Chains
Without polymorphism, adding a new shape (Triangle) forces you to hunt down every if (shape.type === 'circle') ... else if ... block. With polymorphism, you simply create a new class that implements area(), and existing callers work automatically.
Fill-in-the-Blank Exercise
Polymorphic Method Dispatch
Sum the area of any list of shapes by calling the shared area() method.
function totalArea(shapes) {
return shapes.reduce((sum, s) => sum + s.(), 0);
}Try It Yourself (Live OOP Playground)
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. How does polymorphism make a codebase easier to extend?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.