Lesson · Inheritance & Polymorphism
Designing inheritance: is-a forever, or a trap
18 min readInheritance Design
Extending is a forever promise: the parent's future changes, its internal self-use, and its full API all become yours to live with. Substitution and composition decide which hierarchies deserve the promise.
The stack with a bottom hatch
Extending a library class to reuse it feels clever until the library shows up in your type. This stack inherits every method of ArrayList:
class Stack<T> extends ArrayList<T> { void push(T item) { add(item); } // the top of the pile T pop() { return remove(size() - 1); } }
push(1); push(2);builds a tidy pile: the list reads[1, 2].- A caller reaches around the stack and calls
add(0, 9): a born-from-inheritance ArrayList method, inserting below the pile. pop()still returns 2, and the list now reads[9, 1]: a 9 sits under the bottom, where a stack has no door.
The failure is not the caller's; it is the type's. A stack that inherits a bottom hatch is not a stack. extends for reuse smuggles the parent's whole API into your contract, including every method you never wanted to promise.
The substitution rule
Both boxes below hold a Rectangle. One of them lies:
Rectangle r = new Square(); // a Square IS-A Rectangle... is it? r.setWidth(5); r.setHeight(4); System.out.println(r.area()); // 16, not 20
- Substitution: every subclass object must be usable anywhere the parent type is expected, without the caller noticing.
- The promises stay: a subclass may accept more, but never require more (preconditions may weaken, never strengthen); it may deliver more, but never less (postconditions may strengthen, never weaken).
- Invariants keep holding: whatever the parent guarantees about its state stays true after any inherited method runs. A square's width always equalling its height breaks the rectangle's promise that width and height are independent.
- A Square is not a Rectangle in code even though the words sound right in maths class: the rectangle promises independent width and height, and the square cannot keep that promise. The relationship fails the substitution test, so it fails as inheritance.
The test is a scenario, not a word. 'Can I set width and height independently?' is a promise the parent makes. If the subclass cannot keep it, the hierarchy is wrong, however true the sentence sounded.
Three breakages, side by side
Same story three times: a class extended for convenience, and a promise broken by mechanics. Each outcome below was executed with real code, not imagined:
- Extending a collection inherits its grammar; the stack story adds a bottom hatch.
- Extending for counting walks into self-use: the parent calls its own methods, which call your overrides, and the count doubles.
- Extending a value type for geometry breaks substitution: the caller sets width and height independently, and the area disagrees with the arithmetic.
- The composed fix is the same in all three: hold the other object privately, and expose only the methods your type actually means.
Inheritance is not the only way to reuse code. It is the way to promise a type relationship forever. Every failure above came from using it for the smaller thing (reuse) while paying for the bigger one (a permanent contract).
Fragility gallery · extended for reuse, broken by promises
pick a storyThe extension
What actually happened
Verified run: push 1, push 2, then add(0, 9) inserts below the pile. pop() returns 2 and the list reads [9, 1]: a 9 sits under the bottom, where a stack has no door.
The composed fix
Hold a private list; expose push, pop and size. The other methods simply do not exist on your type, so no caller can find a bottom hatch.
Each breakage above was compiled and executed with javac and java before being written down; the numbers are what the runs printed.
Design for inheritance, or forbid it
Java's honest stance: a class is either built for extension or it is not, and the difference is visible in its code:
- Built for extension: the class documents which methods call which (its self-use), offers protected hooks designed to be replaced, and never calls overridable methods from constructors (the child's fields are not ready yet).
- Not built for extension: the class is
final, or its constructors are private with factory methods; nobody can subclass it, so nobody can be broken by its changes. - Records are final by nature: value carriers are not extension points. Extending them was never on the table.
- A `final` method is a targeted refusal: the class may be open, while this one method (often one that keeps the class's invariants) stays untouchable.
Missing documentation is a decision, not a loophole. If nobody wrote down what subclasses may rely on, then nothing is safe to rely on; wrap the class instead of extending it.
Composition: wrap it, do not become it
The default reuse mechanism is a private field and a few forwarding methods. The comparison:
| Question | Extends (is-a) | Holds a field (has-a) |
|---|---|---|
| Relationship | A kind of the parent, permanently | Uses another object; it can be swapped |
| Surface | Inherits every method the parent has, including future ones | Exposes exactly the methods you choose |
| Parent evolves | New methods can break your invariants | Changes stay behind the wrapper wall |
| Substitution test | Must pass wherever the parent is used | No such promise exists |
| Cost | Few lines now, tight coupling forever | A field plus forwarding lines, loose coupling |
- Add a private field of the type you would have extended.
- Expose only the operations your type means: push, pop, size; nothing else leaks.
- Forward each chosen method to the field with one line.
- Keep the field private, so callers and future subclasses cannot reach around your rules.
The wrapper costs a few lines and buys a wall. Nobody can insert below your pile, parent evolution cannot break you, and you can still extend later, in either direction, without anyone's permission.
The inheritance design playbook
Before extends, in order:
- Say the is-a sentence and mean it literally: every subclass object must survive every scenario the parent promises.
- Check the parent: is it documented for extension, and do you control its future? If either answer is no, compose.
- Look for self-use: if the parent calls its own methods internally, your overrides run in places you did not see. Document carefully or wrap.
- Run the substitution test on paper: pick three parent guarantees, and check the subclass keeps every one.
- If extension is genuinely intended, design it: protected hooks, documented self-use, no overridable calls from constructors, and
finaleverywhere else.
Extend with a contract; wrap by default. The one-line sentence about identity decides, and when the sentence is shaky, the private field is always standing by.
Extending is a permanent contract, not a shortcut for reuse
A subclass inherits the parent's present and its future: every method today, and every method added later. Self-use makes overrides run in hidden places, and substitution demands the subclass keep every promise. Design for extension deliberately with documented hooks, forbid it with final when you cannot, and reach for a private field whenever the goal is reuse without the promise.
Interview angles
What is the fragile base class problem?+
Small changes to a parent class can break subclasses in surprising ways, because subclasses depend on the parent's implementation details: which methods it calls, and in what order.
The counting set shows the sharpest case: the parent's addAll calls add internally (self-use), so an override of both counts every element twice. Add a new internal call in a later parent version, and working code breaks without touching the subclass.
// HashSet.addAll calls add per element: the override fires, then addAll counts again set.addAll(List.of("a", "b", "c")); System.out.println(set.count + " vs " + set.size()); // 6 vs 3
Common misconception: That overriding only affects the calls you wrote. Your overrides run wherever the parent's own code calls those methods, including places you never see.
Follow-up: How does composition prevent this whole category?
What does the Liskov substitution principle require, in practice?+
Anywhere the parent type is expected, a subclass object must behave like the parent promises: no stronger preconditions, no weaker postconditions, invariants intact, no surprises.
The Square and Rectangle case fails the test: the rectangle promises independent width and height, and the square cannot keep that promise, so a caller setting both gets an area that contradicts its own arithmetic. The words were true; the promise was not.
Rectangle r = new Square(); r.setWidth(5); r.setHeight(4); System.out.println(r.area()); // 16, not 20: the promise is broken
Common misconception: That substitution is about types compiling, not about behaviour. The compiler accepts the code; only the promise test reveals the lie.
Follow-up: Which design keeps the maths straight without a broken hierarchy?
How do you design a class that is safe to extend?+
Document its self-use (which methods call which), expose deliberate protected hooks, keep constructors free of calls to overridable methods, and test with real subclasses.
Constructors are the sharp edge: an overridable call inside one runs before the child's fields are initialised, so the override sees default values. Hooks like protected void onInsert(...) put the child's extension points where the parent can guarantee a sane state.
class Base { Base() { init(); } // dangerous: init() may be overridden protected void init() { } }
Common misconception: That safe extension is about marking things protected. Protected increases exposure; safety comes from documenting and constraining when the parent calls them.
Follow-up: What breaks when a constructor calls an overridable method?
How do you forbid inheritance when it should not be allowed?+
Mark the class final (nobody can extend it), or keep constructors private and hand out instances through static factory methods.
A final method gives a targeted refusal inside an otherwise open class: invariants the class enforces itself stay unreplaceable while other behaviour remains extensible. Records are final by design, since they are value carriers rather than extension points.
public final class Money { ... } // not an extension point public class Ledger { public final void close() { ... } // the door this class keeps }
Common misconception: That final is unfriendly. It is the accurate statement: this class was not designed for extension, and pretending otherwise breaks subclasses later.
Follow-up: What guarantees does final add beyond refusing subclasses?
When is composition better than inheritance?+
Whenever the goal is reuse and not identity: has-a sentences, wanting only part of the other API, or depending on a class you do not control.
Wrapping costs a field and forwarding lines and buys: a chosen API surface, immunity to the parent's evolution, and the freedom to change the wrapped object (or swap implementations) later. The wrapper can even add behaviour, like counting now done honestly, once per call.
class Stack<T> { private final List<T> items = new ArrayList<>(); // has-a list void push(T item) { items.add(item); } T pop() { return items.remove(items.size() - 1); } }
Common misconception: That wrapping means duplicating everything. You forward only the operations your type promises; the unwrapped methods disappear by design.
Follow-up: What does the wrapper give up compared with extending?