Lesson · Inheritance & Polymorphism
Polymorphism: one call, many classes
18 min readPolymorphism
Hold different objects through one parent type and each answers in its own way. The compiler checks the reference's type; the object's class decides which method runs. Override rules keep that promise safe.
The if/else that keeps growing
You keep a mixed collection of shapes and need their areas. Without polymorphism, every new shape means editing every decision:
for (Object shape : shapes) { if (shape instanceof Square) { total += squareArea((Square) shape); } else if (shape instanceof Rectangle) { total += rectArea((Rectangle) shape); } else if (shape instanceof Circle) { total += circleArea((Circle) shape); } // new Triangle arrives: this list changes again... in every place it appears }
Predict: who should know how a Square computes its area: the loop, or the Square itself? The loop is doing every shape's homework. Inheritance lets each class answer for itself, and one call site serves them all.
One call, decided at runtime
Write the call against the parent type and each object answers with its own method:
Shape[] shapes = { new Square(3), new Rectangle(2, 5), new Circle(2) }; for (Shape s : shapes) { System.out.println(s.area()); // whose area() runs? }
Shape sis the static type: the reference as the compiler sees it. It promises onlyarea()exists.- Each element is a different object: Square, Rectangle, Circle. The runtime class is each object's real type.
- At the call, the compiler checks Shape declares
area(); it does not care which subclass will run. - The runtime finds the object, looks up its class, and runs that class's
area(). This choice at call time is dynamic dispatch.
Substitutability is the quiet half of the trick. Any subclass object may stand where the parent type is expected, and the call still works, because the parent's method list is guaranteed on every subclass.
Dispatch lane · one call, three classes
Current statement
shapes · Shape[]
The call, step by step
Output
nothing printed yet
The array is built: three objects of three classes, held through one element type, Shape. Every element is, as far as the compiler knows, a Shape.
The rules for replacing a method
Overriding means a subclass provides its own version of an inherited method, with the same name and parameters. The compiler enforces the fine print:
| Rule | Allowed | Refused (with the compiler's words) |
|---|---|---|
| Visibility | Same, or wider (package → public) | Narrower: attempting to assign weaker access privileges |
| Return type | Same type, or a subtype: Employee make() → Manager make() | Unrelated types |
| Checked exceptions | Same list, or narrower; none is easiest | Broader: overridden method does not throw Exception |
| static, final, private | Nothing: static methods hide, private methods are not inherited, final methods cannot be replaced | @Override says which: static methods cannot be annotated with @Override; overridden method is final; method does not override or implement a method from a supertype |
- Write
@Overrideon every intended override. The annotation is checked by the compiler, so a typo'd name or wrong parameter list becomes an error instead of a silently new method. - Narrowing the return type is allowed and useful: a
Manager clone()may returnManager, and callers ofManagerno longer need a cast. - Keep the meaning stable. An override may do the job better, faster or more specifically; if it changes what the method means, every caller built on the parent's promise quietly breaks.
`@Override` is a seat belt, not decoration. It is the difference between 'your override works' and 'you accidentally wrote a near-duplicate that is never called'.
Who decides: the compiler or the object?
Two decisions happen at different times, and mixing them up causes the classic surprise:
| The choice | Made when | Looks at | Example |
|---|---|---|---|
| Which overload runs | Compile time | The static types written in the call | print(int) vs print(double) |
| Which override runs | Runtime | The object's actual class | s.area() in the loop |
| A static/private/final call | Compile time (nothing to choose) | The static type | No dispatch at all |
Overloads: the compiler decides from what you wrote. Overrides: the object decides from what it is. Hold one shape in your head: the compiler only ever sees the reference's type; the object brings its own class to the call.
The polymorphism playbook
Writing code that bends without breaking, in order:
- Declare variables and parameters as the most general type you need (
Shape s, notSquare s) so every subtype fits. - Give the parent a method every subtype can answer; each subclass implements it with
@Override. - Replace chains of
instanceofplus casts with one call; if a chain survives, a method is missing somewhere. - Add a new subtype and change nothing else: that is the test of working polymorphism, and it should pass with zero edits to existing loops.
- Keep overrides honest: same meaning, wider never narrower, and exceptions never broader.
One call site, many classes, no branches. When you catch yourself asking 'what kind of object is this?' before every call, the answer belongs inside the classes instead.
The compiler reads the reference; the object runs the method
Polymorphism means subclasses may stand in for their parent type, and each answers a call with its own version. Compile time checks that the declared type has the method; call time picks the object's class. The override rules (visibility, return types, exceptions) exist so every substitute keeps the parent's promise.
Interview angles
Walk through what happens at `s.area()` when `s` is declared `Shape` but holds a Circle.+
The compiler checks that Shape declares area(); at the call, the runtime finds the object's class (Circle) and runs Circle.area(). That late choice is dynamic dispatch.
The declared type decides what calls are legal; the object decides which implementation runs. That split is why one loop over Shape[] can serve every current and future subclass without editing.
Shape s = new Circle(2); // declared Shape, runtime class Circle System.out.println(s.area()); // Circle.area() runs: 12.6
Common misconception: That the variable's type picks the method body. The variable's type only decides what may be called; the object's class supplies the code.
Follow-up: What method set must the declared type guarantee?
How do overloading and overriding differ at call time?+
Overloads are chosen at compile time from the static types you wrote; overrides are chosen at runtime from the object's class.
Both can coexist in one call chain: the compiler picks which signature (overload) matches the arguments, then the runtime picks the implementation (override) for that signature in the object's class.
print(1); // compiler picks print(int) print(1.0); // compiler picks print(double) shape.area(); // runtime picks the class's override
Common misconception: That the compiler can resolve overridden calls. It cannot in general: the object that arrives at runtime decides, which is exactly what makes substitution work.
Follow-up: Why can a static method not be dispatched this way?
What rules must an override follow?+
Same name and parameters; visibility same or wider; return type same or a subtype (covariant); checked exceptions same or narrower; and static, final, private methods cannot be overridden at all.
The rules protect substitutability: callers written against the parent must keep compiling and keep meaning the same thing. @Override makes the compiler verify all of this instead of trusting your typing.
class Employee { public Employee copy() { ... } } class Manager extends Employee { @Override public Manager copy() { ... } // covariant return: legal and useful }
Common misconception: That an override must look exactly like the original. Return types may narrow to a subtype, and visibility may widen; only narrowing visibility and broadening exceptions are refused.
Follow-up: What compile error appears when a return type is unrelated?
Why is `@Override` recommended even though it is optional?+
The compiler verifies it: a wrong parameter list, a typo in the name, or an attempt to override a static/private method all become errors instead of silently new methods.
Without the annotation, public boolean equals(MyType other) (wrong parameter type) compiles fine and is simply never used by collections; with @Override, the compiler demands a real match. The annotation costs nothing at runtime.
@Override public boolean equals(Object other) { ... } // the only signature collections ever call
Common misconception: That a near-duplicate method will still be found at runtime. The runtime matches signatures exactly; a near miss is dead code that looks alive.
Follow-up: Which signature do collections actually call for equality?
What makes static methods different under polymorphism?+
They have no receiver object to dispatch to. Calls are bound at compile time from the reference's type, so a matching subclass method only hides the parent's rather than replacing it.
That is why utilities are static (Math.abs) and why overriding is impossible for them: no object, no runtime choice. The next lesson (What Is Not Overriding) takes hiding, shadowed fields and private methods apart in detail.
class A { static void greet() { System.out.println("A"); } } class B extends A { static void greet() { System.out.println("B"); } } A ref = new B(); ref.greet(); // A: the reference's type decided, at compile time
Common misconception: That a subclass static method 'overrides' the parent's. It hides it; the call you get depends on the reference type in the source, which surprises readers.
Follow-up: Why does the compiler pick from the reference type for statics?