Java OOP · Module 12
Favor composition over inheritance
Why the most famous advice in OOP exists — and when to ignore it
What you'll be able to do
- Explain the fragile base class problem in your own words
- Show how composition lets behaviour change at run time
- Convert an inheritance design into a composition design
- Name the cases where inheritance is still the right answer
Composition vs Inheritance
Inheritance is the tightest coupling in the language
`extends` gives you code for free — and signs you up for every future change in the parent, whether you want it or not.
When you write class B extends A you inherit four things at once:
1. A's public API — every method callers can use on your object.
2. A's protected internals — fields and helpers you now depend on.
3. A's future changes — add a method to A in six months and every subclass silently receives it.
4. A's substitutability — your object can be passed anywhere an A is expected, so it must behave like one.
That is why inheritance is called the tightest coupling available. It is also why the advice 'favor composition over inheritance' exists: composition depends only on the collaborator's public methods, which is a much thinner promise.
The fragile base class problem
The classic demonstration: a counting list.
``java
class CountingList extends ArrayList<String> {
private int added = 0;
@Override
public boolean add(String item) {
added++;
return super.add(item);
}
@Override
public boolean addAll(Collection<? extends String> items) {
added += items.size();
return super.addAll(items); // ⚠️ addAll internally calls add()
}
}
`
Add three items with addAll and the counter reports **six**, because the parent's addAll calls add for each element — an implementation detail that was never part of its documented contract. The subclass is correct today and broken tomorrow if the parent changes how addAll` works.
With composition the bug cannot happen: the wrapper holds a list, counts once, and forwards. It never sees or depends on the internals.
Inheritance vs composition
| Criterion | Inheritance (`extends`) | Composition (field + delegation) |
|---|---|---|
| Relationship | IS-A | HAS-A |
| Decided at | compile time, permanently | run time, swappable |
| Coupling | very tight — includes protected internals | loose — public methods only |
| How many sources of behaviour | one parent | as many collaborators as you like |
| Effect of a parent change | propagates automatically, sometimes breaking you | contained behind the collaborator's API |
| Code to write | almost none | delegating methods |
| Testability | parent's behaviour comes along in every test | inject a fake collaborator |
| Encapsulation | weakened (subclass sees protected state) | preserved |
| Right when | a true, stable IS-A family with shared state | you need behaviour, not identity |
'Favor' is not 'never inherit'. Inheritance remains the right tool for genuine families — `SavingsAccount extends Account`, `Square extends Shape` — especially with an abstract parent you own and control.
With `class ElectricCar extends Car` you would need a *new object* to change engines. Here one car swaps engines mid-run — add a `HybridEngine` and switch to it.
Converting inheritance into composition
- Ask the IS-A question honestly. If the sentence is false, stop — you already have your answer.
- Replace
extends Awith a private field of type A (or better, of an interface A implements). - Add small public methods that forward to that field — expose only what callers actually need.
- Accept the collaborator in the constructor so it can be swapped or faked in tests.
- Delete the inherited methods you never wanted; that shrinking API is the real win.
Adding a second dimension of variation
Inheritance explodes
one class per combination
- Every new engine doubles the class count
- Shared code gets copied between branches
- A car can never change engine
Composition multiplies
parts combine freely
- A new engine is one new class, no edits
- Combinations are created, not declared
- Behaviour can change at run time
The interview answer
'Inheritance couples me to the parent's implementation and its future changes, and I only get one parent. Composition depends on a public API, lets me combine several behaviours, and can be changed at run time. So I inherit only for a genuine, stable IS-A relationship — usually from an abstract class or interface I control — and compose everything else.'
Prove it — coding challenges
Common mistakes
Extending a class from a library just to reuse a few methods.Reading the advice as 'inheritance is bad'.Composing but exposing the collaborator (`getEngine()`), so callers drive it directly.Lesson playground
An employee gains abilities by holding them, not by inheriting a class per specialisation. Add a `Testing` skill and give it to Sara — no new Employee subclass needed.
Check understanding
Quiz
Question 1 of 5
The collaborator is replaced while the program runs. What is printed?
Summary
- `extends` inherits the parent's API, internals, future changes and substitutability — the tightest coupling in Java.
- The fragile base class problem breaks subclasses when a parent's internal calls change.
- Composition depends on public methods only, combines many behaviours and can change at run time.
- Inherit for a genuine IS-A family with shared state; compose for everything else.