Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 12

Favor composition over inheritance

Why the most famous advice in OOP exists — and when to ignore it

24m60 XP
→→→

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
1

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

CriterionInheritance (`extends`)Composition (field + delegation)
RelationshipIS-AHAS-A
Decided atcompile time, permanentlyrun time, swappable
Couplingvery tight — includes protected internalsloose — public methods only
How many sources of behaviourone parentas many collaborators as you like
Effect of a parent changepropagates automatically, sometimes breaking youcontained behind the collaborator's API
Code to writealmost nonedelegating methods
Testabilityparent's behaviour comes along in every testinject a fake collaborator
Encapsulationweakened (subclass sees protected state)preserved
Right whena true, stable IS-A family with shared stateyou 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.

Composition can change behaviour while the program runs

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.

Output
Press Run to execute this example.

Converting inheritance into composition

  1. Ask the IS-A question honestly. If the sentence is false, stop — you already have your answer.
  2. Replace extends A with a private field of type A (or better, of an interface A implements).
  3. Add small public methods that forward to that field — expose only what callers actually need.
  4. Accept the collaborator in the constructor so it can be swapped or faked in tests.
  5. 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

Main.java
1PetrolCar
2ElectricCar
3PetrolSportsCar
4ElectricSportsCar
5PetrolFamilyCar
6ElectricFamilyCar // 2 × 3 = 6 classes
  • Every new engine doubles the class count
  • Shared code gets copied between branches
  • A car can never change engine

Composition multiplies

parts combine freely

Main.java
1new Car("Sports", new PetrolEngine());
2new Car("Sports", new ElectricEngine());
3new Car("Family", new ElectricEngine());
4// 1 class + N engines
  • 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

WrongExtending a class from a library just to reuse a few methods.
WhyYou inherit its whole API and become hostage to its internals — the fragile base class problem.
FixWrap it: hold an instance and expose only the operations you need.
WrongReading the advice as 'inheritance is bad'.
WhyPolymorphism, abstract classes and interfaces all rely on inheritance of type; the course project uses it deliberately.
FixInherit for identity and shared state; compose for behaviour.
WrongComposing but exposing the collaborator (`getEngine()`), so callers drive it directly.
WhyYou get the boilerplate of composition with the coupling of inheritance.
FixKeep the field private and publish intent-revealing methods.

Lesson playground

Free practice

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.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

The collaborator is replaced while the program runs. What is printed?

Main.java
1interface Voice {
2 void speak();
3}
4
5class Loud implements Voice {
6 @Override
7 public void speak() {
8 System.out.println("HELLO");
9 }
10}
11
12class Quiet implements Voice {
13 @Override
14 public void speak() {
15 System.out.println("hello");
16 }
17}
18
19class Robot {
20 private Voice voice;
21
22 Robot(Voice voice) {
23 this.voice = voice;
24 }
25
26 void setVoice(Voice voice) {
27 this.voice = voice;
28 }
29
30 void talk() {
31 voice.speak();
32 }
33}
34
35public class Main {
36 public static void main(String[] args) {
37 Robot robot = new Robot(new Loud());
38 robot.talk();
39
40 robot.setVoice(new Quiet());
41 robot.talk();
42 }
43}

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.