Notes
The problem
Here is a fare calculator in a ride app. It checks a type string: auto, mini or S U V, and runs a different formula for each. It works, but the same chain appears again in the code for arrival time, map icon, cancel fee and seat count. Adding a pool ride means finding and editing every chain, and missing one is a bug that only shows up when someone books a pool ride.
long fare(String type, int km, int min) {
if (type.equals("AUTO"))
return 30 + 12 * km;
else if (type.equals("MINI"))
return 50 + 15 * km + min;
else if (type.equals("SUV"))
return Math.max(300, 80+22*km+2*min);
throw new IllegalArgumentException(type);
}
// same chain again in eta(), icon(),
// cancelFee(), seats() ... The idea
Polymorphism means code written against one type works with many types, and each object decides how to respond. The booking service just says: ride, what is your fare for eight kilometres and twenty minutes? It never asks which kind of ride it is. The object already knows what it is, so the decision moves from a chain of checks into the objects themselves.
- polymorphism: code written
- against one type works with
- many types, and each object
- decides how to respond
- caller says: ride.fare(8, 20)
- it never asks "which ride?"
- the object already knows
The structure
Each branch of the old chain becomes a class. The RideOption interface declares fare. Auto ride returns thirty plus twelve per kilometre. Mini cab adds a per minute charge. S U V ride applies a minimum fare of three hundred. Each formula lives with its ride type, and the related methods, like arrival time or cancel fee, can live there too. No more string type codes.
interface RideOption {
String name();
long fare(int km, int minutes);
}
class AutoRide implements RideOption {
public long fare(int km, int min) {
return 30 + 12L * km;
}
}
// MiniCab, SuvRide: their own formula Run-through
The booking service loops over the available rides and calls fare with eight kilometres and twenty minutes. The auto answers one hundred and twenty six. The mini cab answers one hundred and ninety. The S U V works out two hundred and ninety six, then lifts it to its minimum of three hundred. The calling code is the same single line each time.
Dynamic dispatch
How does Java know which fare to run? A variable has a static type, here RideOption, which the compiler checks. The object has a runtime type, here mini cab. The compiler only confirms that RideOption has a fare method. When the program runs, the virtual machine looks at the actual object and calls mini cab's version. This is dynamic dispatch, also called late binding.
RideOption r = new MiniCab(); // static type: RideOption // runtime type: MiniCab r.fare(8, 20); // compiler: does RideOption // have fare(int, int)? yes // at runtime: run MiniCab.fare this is called late binding
Adding a type
Now add a pool ride. Write one new class, pool ride, that implements RideOption with its own cheaper formula, and add it where the list of rides is built. The booking service, the receipts and every other caller stay exactly as they were. Compare that with hunting down every if else chain. This is also the open closed principle, which the SOLID unit covers next.
Overloading
The other kind is compile time polymorphism, or overloading. A class has several methods with the same name but different parameter lists. Receipts can print a fare, a fare with a coupon, or a fare with a tip percentage. The compiler picks the version from the number and types of the arguments, before the program ever runs. The return type alone cannot tell overloads apart.
String print(long fare) String print(long fare, String coupon) String print(long fare, int tipPercent) print(190) // first print(190, "FEST10") // second print(190, 10) // third chosen at compile time from the argument types
The overloading trap
Here is the trap that appears in interviews. Two overloads: label taking an Object and label taking a String. A variable of type Object holds the text MINI. Calling label picks the Object version, because overloads are chosen at compile time from the static type of the variable. Only overriding looks at the real object at runtime. Mixing up the two is a classic source of bugs.
String label(Object o) { return "obj"; }
String label(String s) { return "text"; }
Object x = "MINI";
label(x); // "obj", not "text"!
overloading: static type decides
overriding: runtime type decides Not polymorphic
Some things do not behave polymorphically. A field with the same name in a parent and a child is hidden, not overridden, and the variable type decides which one you read. Static methods belong to the class and are chosen by the class name. Private methods cannot be overridden at all. Only non private, non static instance methods are dispatched on the runtime type.
- fields: picked by the
- variable type (hiding)
- static methods: by the
- class name, not the object
- private methods: not
- inherited, never overridden
- constructors: not inherited
- only instance methods
- are dynamically dispatched
Casting is a smell
When you see code that asks, is this ride an S U V, and casts it to add a surcharge, the decision has leaked back to the caller. Instead, put the surcharge inside the S U V class, so the caller can just ask for the fare. A few type checks are fine at the edges, such as reading input, but in the core logic they usually mean a method is missing.
// smell if (r instanceof SuvRide s) fare = s.fare(km, min) + 50; // fix: ask the object fare = r.fare(km, min); // SuvRide adds its own surcharge
In the JDK
You use polymorphism all the time. A List variable can hold an ArrayList or a LinkedList, and add works for both. Printing any object calls the real class's toString. A Comparator has one compare method but endless orderings, and a thread runs any Runnable without knowing what it does. Each time, the caller writes against one type, and the objects provide the behaviour.
- List l = new ArrayList<>()
- or new LinkedList<>()
- println(obj) calls the real
- toString() of any object
- Comparator: one compare(),
- many orderings
- Runnable: one run(),
- any task for a thread
When not to
Polymorphism is not always the answer. If there are three fixed values, used in one place, a simple switch is clear and short. Classes win when new types keep arriving, or when several methods switch on the same type code. An enum with a method per constant is a good middle ground: each constant carries its own behaviour, and the compiler knows every possible value.
- classes win when:
- types keep being added
- several methods switch on
- the same type code
- a switch is fine when:
- values are fixed and few
- one place uses them
- an enum with methods is a
- good middle ground
In interviews
In design rounds, polymorphism is the answer to almost every if else chain on a type. Parking fees by vehicle, payment methods, notification channels, the moves of chess pieces, and the states of a vending machine. When you see a type code, turn each branch into a class behind one interface. The usual mistakes are instanceof chains in core logic and confusing overloading with overriding.
- parking: fee per vehicle
- payments: card, UPI, wallet
- notifications: SMS, email
- chess: each piece moves
- in its own way
- vending: state per stage
- mistake: instanceof chains
- in the core logic