Open any chat app and look at the Send button. You press the same button whether you typed a message, picked a photo or recorded a voice note, but the app does something different each time. Text goes out straight away, a photo gets compressed and uploaded, a voice note gets encoded first. One action, several behaviors. That is polymorphism.
In one line: the same method call does different things depending on the object that receives it.
The Send button
Whoever presses Send never thinks "is this a photo? then I should compress it". They just press Send, and each kind of message knows how to send itself. If the app adds stickers or documents next month, the Send button does not change at all.
One Send action; each message type does its own work
1. What Is Polymorphism?
The word is Greek: poly means many, morph means form. In OOP it means you write code against a general type, a parent class or an interface, and the actual object decides which code runs.
The calling code says what it wants: message.render(). Each object decides how to do it. Polymorphism leans on the two previous topics. Inheritance creates the is-a family, and abstraction gives that family a shared contract.
2. Why Polymorphism Matters
Without it you end up writing if (type == "IMAGE") ... else if (type == "VOICE") ... in every place that deals with messages. With it, each class carries its own behavior and those chains disappear.
A new type becomes a new class, and the code that works with the general type stays untouched. That is the Open/Closed Principle again. Callers depend on the abstraction (Message, Coupon) rather than on every concrete class, so the pieces stay loosely coupled. And testing gets easier, because you can hand in a fake object that follows the same contract instead of a real service.
3. Types of Polymorphism
There are two kinds, and the difference is when the program decides which code to run.
Compile-time polymorphism is decided by the compiler; runtime polymorphism by the actual object
| Compile-time (static) | Runtime (dynamic) | |
|---|---|---|
| Also called | Overloading, early binding | Overriding, late binding, dynamic dispatch |
| Where | Same class, same name, different parameters | Parent and child, same name, same parameters |
| Decided by | The compiler, from the argument types | The actual object, while the program runs |
| Needs inheritance? | No | Yes (a parent class or an interface) |
| Importance in LLD | Useful convenience | The core tool for flexible designs |
4. Compile-Time Polymorphism
4.1 Method Overloading
Overloading means one class has several methods with the same name but different parameter lists: a different number of parameters, different types, or the same types in a different order. The compiler looks at the arguments in each call and picks the matching version before the program ever runs.
Say a bus booking app charges Rs.2 per km. Sometimes it needs the fare for one person, sometimes for a group, sometimes with a discount, and sometimes for an AC seat. That is four fare() methods sharing one name:
The compiler picks the fare() whose parameter list matches the call
Output
1 passenger, 150 km: Rs.300
3 passengers, 150 km: Rs.900
3 passengers, 150 km, 20% senior discount: Rs.720
1 AC seat, 150 km: Rs.600One rule to remember: the return type on its own is not enough to tell overloads apart. int fare(int km) and double fare(int km) cannot both exist, because the compiler would have no way to know which one a call meant.
4.2 Operator Overloading
Some languages let you give operators like + and == a meaning for your own classes, so that adding two prices could read tea + snacks. Java deliberately does not. The only built-in case is + joining strings. In Java you write a method with a clear name instead:
Output
Tea + snacks: Rs.249.50 + Rs.120.75 = Rs.370.25
3 x tea: Rs.748.50
Same price? yesMethods such as plus() and equals() do the same job and leave no doubt about what is happening. Java still calls toString() for you whenever an object is joined into a string, which is a small piece of polymorphism in its own right.
Whatever the language, the meaning should be obvious. Adding two amounts of money makes sense; "adding" an order to a customer does not.
5. Runtime Polymorphism (Method Overriding)
This is the kind that matters most in Low-Level Design. A child class overrides a parent method, keeping the same name and parameters. When you call that method through a variable of the parent type, the program looks at the actual object at runtime and runs the child's version. This is called dynamic dispatch.
Every message type overrides render(); callers only know Message
Output
[Text] Ravi: Standup at 10?
[Image] Priya: team_lunch.jpg compressed 2400 KB -> 600 KB
[Voice] Kiran: 42s voice note, transcript queued
[Voice] Anitha: 8s voice note, transcript queuedLook at show(Message m). It takes the parent type and never asks which child it got, yet each message prints in its own format. A StickerMessage or DocumentMessage would be one new class, with no change to show().
5.1 Declared Type vs Actual Type
The line Message m = new VoiceMessage("Anitha", 8); involves two different types, and it helps to keep them apart.
The declared type decides what you may call; the actual object decides which code runs
The declared type, also called the reference type, is Message. The compiler uses it to check which methods you are allowed to call. m.render() is fine, but a method that only VoiceMessage has would not compile.
The actual type, the type of the object itself, is VoiceMessage. At runtime the search for render() starts there. If VoiceMessage does not override it, the search moves up to the parent.
Putting a child object into a parent-type variable is called upcasting, and it is always safe because a child is a parent. Going the other way, downcasting with something like (VoiceMessage) m, needs a check, and needing it is usually a hint that the parent is missing a method.
5.2 Rules of Overriding
| Rule | Java |
|---|---|
| Enable overriding | On by default for instance methods |
| Mark the override | @Override (catches typos) |
| Block overriding | final method |
| Not polymorphic | static and private methods, fields |
| Access level | Cannot be more restrictive than the parent |
One trap catches a lot of people: only instance methods are polymorphic. A static method or a field with the same name in the child is hidden, not overridden. So for Message m = new TextMessage(...), the declared type Message decides which static method and which field you get. Keep fields private and put behavior in instance methods, and this never bites you.
6. Polymorphism with Interfaces and Abstract Classes
Runtime polymorphism does not need a concrete parent class. In Java it usually comes from one of two places. An abstract class gives you a family with shared code, like Employee in the payroll example from the last article. An interface gives you a pure contract for classes that share a capability but no code, like Coupon below.
Either way the calling code looks the same: it calls the method and lets the object decide.
7. Practical Example: Coupons at Checkout
A food delivery app offers three coupons: a flat Rs.150 off orders above Rs.999, 20% off up to a maximum of Rs.200, and free delivery (delivery costs Rs.49). At checkout the app has to try every coupon and apply whichever saves the customer the most. The marketing team adds new coupon types every month.
Without polymorphism the checkout would hold an if for every coupon type, and every new coupon would mean editing and re-testing it. With polymorphism, every coupon implements one contract and the checkout only knows about that contract.
Checkout depends only on the Coupon interface
This is what happens for a Rs.600 cart:
Checkout asks each coupon for its discount and keeps the best one
Output
Cart Rs.1200 + delivery Rs.49
FLAT150 -> Rs.150 off
SAVE20 -> Rs.200 off
FREEDEL -> Rs.49 off
Best: SAVE20, pay Rs.1049
Cart Rs.600 + delivery Rs.49
FLAT150 -> not applicable
SAVE20 -> Rs.120 off
FREEDEL -> Rs.49 off
Best: SAVE20, pay Rs.529
Cart Rs.200 + delivery Rs.49
FLAT150 -> not applicable
SAVE20 -> Rs.40 off
FREEDEL -> Rs.49 off
Best: FREEDEL, pay Rs.200Why This Design Works
pay() contains no type checks. It never asks "is this a flat coupon?". Each coupon works out its own discount, including the case where it does not apply.
New coupons leave Checkout alone. A Buy 1 Get 1 offer or a first-order coupon is one new class, and since Checkout did not change, it does not need re-testing.
The best coupon depends on the cart, and the same loop copes with all of them. At Rs.1200 the percentage coupon wins; at Rs.200 free delivery wins.
If this looks familiar, it is the Strategy pattern: each coupon is an interchangeable strategy behind one interface. It comes back in the design patterns section.
8. Common Mistakes
- Type checks instead of overriding. An
if (m instanceof ImageMessage)in the caller means that behavior belongs inside the class. Add or override a method instead. - Mixing up overloading and overriding. Overloading is the same class with different parameters, picked at compile time. Overriding is a child class with the same parameters, picked at runtime.
- Changing the parameter list by accident.
render(int width)in a child does not overriderender(); it adds an overload, and the parent's version still runs.@Overridecatches this for you. - Expecting
staticmethods or fields to be polymorphic. They are picked by the declared type, not the actual object. - Overrides that break what callers expect. A child's version must still do what the parent promised. A
discount()that returns a negative number breaks every checkout that uses it. - Overloads that do different jobs. All the overloads of a method should do the same thing. If
fare(int)returns a price andfare(String)prints a ticket, they are two different methods and deserve two different names.
Summary
Polymorphism lets one method call behave differently depending on the object that receives it. Compile-time polymorphism is overloading, where the compiler picks the version from the arguments. Java has method overloading but no operator overloading. Runtime polymorphism is overriding, where the actual object picks the version, and it is the main tool for building flexible LLD designs.
The declared type decides what you are allowed to call; the actual type decides which code runs. Whenever you find a type check or a long if-else chain, try replacing it with overridden methods behind a common parent or interface.
That completes the four pillars of OOP: encapsulation, abstraction, inheritance and polymorphism. Next you will see how classes relate to each other through association, aggregation and composition.