Inheritance vs composition
When a class should extend another and when it should hold parts instead. The class explosion, the fragile base class, and favour composition, with Java and Python code.
On this page
The problem: a family tree that keeps growing
A toy company models robots. Some walk, some fly; some have a claw, some a laser. The first design uses inheritance for everything: a base Robot, then WalkingRobot and FlyingRobot, then WalkingClawRobot, WalkingLaserRobot, FlyingClawRobot, FlyingLaserRobot.
Then marketing adds swimming and a camera. Three ways to move times three tools is nine classes; add a third feature with two options and it is eighteen. Worse, the "walk" code is copied into every walking class, and a robot that should switch from walking to flying mid-game can't, because an object cannot change its class.
One subclass per combination: the class explosion
- But inheritance gets out of hand. A toy company makes robots that walk or fly, with a claw or a laser. One subclass per combination… then add swimming and a camera. This is a class explosion.
The idea: "is a" versus "has a"
Inheritance lets a class (the subclass, or child) reuse and extend another (the superclass, or parent). The subclass gets the parent's fields and methods and can override methods to do its own version. It models an "is a" relationship: a Dog is an Animal.
A Dog is an Animal, and overrides speak()
- Inheritance lets one class reuse another. A Dog is an Animal, so Dog extends Animal and gets its name and eat() for free.
- A subclass can override a method to do its own version. Call speak() on any animal and you get the right sound.
Composition builds an object from other objects it holds as fields. It models "has a": a Robot has a Mover and has a Tool, and delegates to them (calls their methods to do the work). Each part is a small class behind an interface, and any combination is just a different set of parts.
A robot built from parts, swapped at run time
- Composition builds a robot from parts instead. A Robot has a Mover and has a Tool. Each part is a small class, and you plug in any combination.
- Parts can even be swapped while the program runs: robot.setMover(new Fly()). An object can never change its class, but it can change its parts. That’s why the rule of thumb is: favour composition over inheritance.
With composition, three movers and three tools are six small classes, not nine robot classes, and new features add classes linearly rather than multiplying them.
How it works in code
Inheritance, done properly
abstract class Animal {
private final String name; // private: subclasses use name()
protected Animal(String name) { this.name = name; }
public String name() { return name; }
public String eat() { return name + " eats"; } // shared behaviour, inherited as is
public abstract String speak(); // every animal must provide its own
}
class Dog extends Animal {
Dog(String name) { super(name); } // run the parent's constructor first
@Override
public String speak() { return name() + " says woof"; }
}
class Cat extends Animal {
Cat(String name) { super(name); }
@Override
public String speak() { return name() + " says meow"; }
@Override
public String eat() { return super.eat() + ", slowly"; } // extend, not replace
}from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name: str):
self._name = name
@property
def name(self) -> str:
return self._name
def eat(self) -> str: # shared behaviour, inherited as is
return f"{self._name} eats"
@abstractmethod
def speak(self) -> str: ... # every animal must provide its own
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} says woof"
class Cat(Animal):
def speak(self) -> str:
return f"{self.name} says meow"
def eat(self) -> str:
return super().eat() + ", slowly" # extend, not replacesuper(...) runs the parent's constructor; super.eat() (Python super().eat()) calls the parent's version of an overridden method. The @Override annotation makes the compiler check you really are overriding something, which catches typos like speek().
Composition: the robot
interface Mover { String move(); }
interface Tool { String use(); }
class Walk implements Mover { public String move() { return "walks"; } }
class Fly implements Mover { public String move() { return "flies"; } }
class Swim implements Mover { public String move() { return "swims"; } }
class Claw implements Tool { public String use() { return "grabs with a claw"; } }
class Laser implements Tool { public String use() { return "fires a laser"; } }
class Robot {
private final String name;
private Mover mover; // has a Mover
private final Tool tool; // has a Tool
Robot(String name, Mover mover, Tool tool) {
this.name = name; this.mover = mover; this.tool = tool;
}
void setMover(Mover mover) { this.mover = mover; } // swap a part at run time
String act() { return name + " " + mover.move() + " and " + tool.use(); } // delegate
}
public class Main {
public static void main(String[] args) {
Robot r = new Robot("R2", new Walk(), new Claw());
System.out.println(r.act()); // R2 walks and grabs with a claw
r.setMover(new Fly());
System.out.println(r.act()); // R2 flies and grabs with a claw
System.out.println(new Robot("Nemo", new Swim(), new Laser()).act());
}
}from typing import Protocol
class Mover(Protocol):
def move(self) -> str: ...
class Tool(Protocol):
def use(self) -> str: ...
class Walk:
def move(self): return "walks"
class Fly:
def move(self): return "flies"
class Swim:
def move(self): return "swims"
class Claw:
def use(self): return "grabs with a claw"
class Laser:
def use(self): return "fires a laser"
class Robot:
def __init__(self, name: str, mover: Mover, tool: Tool):
self.name = name
self.mover = mover # has a Mover
self.tool = tool # has a Tool
def act(self) -> str: # delegate to the parts
return f"{self.name} {self.mover.move()} and {self.tool.use()}"
if __name__ == "__main__":
r = Robot("R2", Walk(), Claw())
print(r.act()) # R2 walks and grabs with a claw
r.mover = Fly() # swap a part at run time
print(r.act()) # R2 flies and grabs with a claw
print(Robot("Nemo", Swim(), Laser()).act())This is the Strategy pattern in miniature: each part is a strategy the robot delegates to.
The fragile base class problem
Inheritance has a subtler cost than class counts. A subclass depends not only on what the parent's methods promise, but on how they are implemented. When the parent changes its internals, a subclass that was correct yesterday breaks today, even though nobody touched it. This is the fragile base class problem.
The classic example (from Joshua Bloch's Effective Java): count how many items were ever added to a set by extending HashSet.
import java.util.*;
class CountingSet<E> extends HashSet<E> {
private int added = 0;
@Override public boolean add(E e) { added++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
added += c.size();
return super.addAll(c); // surprise: HashSet's addAll calls add() for each item
}
int added() { return added; }
}
CountingSet<String> s = new CountingSet<>();
s.addAll(List.of("a", "b", "c"));
System.out.println(s.added()); // 6, not 3: every item was counted twiceclass Bag: # a library class you don't own
def __init__(self):
self._items = []
def add(self, x):
self._items.append(x)
def add_all(self, xs):
for x in xs:
self.add(x) # an implementation detail you can't see
class CountingBag(Bag):
def __init__(self):
super().__init__()
self.added = 0
def add(self, x):
self.added += 1
super().add(x)
def add_all(self, xs):
xs = list(xs)
self.added += len(xs)
super().add_all(xs) # calls our add() again for each item
b = CountingBag()
b.add_all(["a", "b", "c"])
print(b.added) # 6, not 3Delete the addAll override and it works, but only by relying on HashSet's current implementation. If a future version made addAll stop calling add, the count would silently drop to 0 for bulk adds. Either way, the subclass is correct only by accident.
Composition removes the dependency on internals: wrap a set instead of extending one, and count in your own methods.
import java.util.*;
class CountingSet<E> {
private final Set<E> inner = new HashSet<>(); // has a Set
private int added = 0;
public boolean add(E e) { added++; return inner.add(e); }
public boolean addAll(Collection<? extends E> c) {
boolean changed = false;
for (E e : c) changed |= add(e); // our own add: counted exactly once
return changed;
}
public boolean contains(Object o) { return inner.contains(o); }
public int size() { return inner.size(); }
public int added() { return added; }
}class CountingSet:
def __init__(self):
self._inner = set() # has a set
self.added = 0
def add(self, x):
self.added += 1
self._inner.add(x)
def add_all(self, xs):
for x in xs:
self.add(x) # counted exactly once, whatever set does inside
def __contains__(self, x):
return x in self._inner
def __len__(self):
return len(self._inner)The wrapper exposes only the methods it needs. If callers need the full Set interface, write a forwarding class that implements Set and passes each method through (Guava ships ForwardingSet for exactly this).
Options and trade-offs
Inheritance (extends) | Composition (has a) | Interface (implements) | |
|---|---|---|---|
| Relationship | X is a Y, always | X has a Y | X can do Y |
| Good at | Sharing code and a type in one step; abstract base classes with a template | Mixing independent features; swapping behaviour at run time | Letting unrelated classes be used the same way |
| Weak at | Combinations, run-time change, coupling to the parent's internals | Forwarding boilerplate, more objects | Sharing state or a lot of code |
| Changes at run time? | No: an object never changes class | Yes: swap the part | Fixed per class |
| Use when | A stable "is a" with real shared behaviour (often a framework base class) | Features vary independently or change often | You need a type many classes can fill |
The test from the chapter: would "X is a Y" be true everywhere and always? A Square is a Rectangle in geometry, but if Rectangle has setWidth, a square that keeps its sides equal breaks code that sets width and height separately. That is a Liskov substitution failure, and a sign the relationship is not really "is a" in code.
Inheritance is still right for a true "is a"
- Inheritance is still right for a true “is a” with shared behaviour, like Dog and Animal. The test: would “X is a Y” always be true, everywhere? If it’s really “X has a Y” or “X can do Y”, use composition or an interface.
When inheritance is the right call
- A true, stable "is a" with shared behaviour:
DogandAnimal,IOExceptionandException. - Frameworks designed for it:
HttpServlet, Android'sActivity, Python'sunittest.TestCase. The base class documents which methods to override. - Template Method: a base class fixes the steps of an algorithm and subclasses fill in a few (see the Template Method pattern).
- Closed families: Java
sealedclasses (sealed interface Shape permits Circle, Square) let you inherit safely within one module because nobody else can extend.
If you write a class meant to be extended, document which methods call which (Bloch: "design and document for inheritance, or else prohibit it"). Otherwise mark it final.
Multiple inheritance, mixins and the MRO
Java allows one superclass but many interfaces; since Java 8, interfaces can carry default methods, and if two interfaces supply the same default the class must override it and choose (A.super.m()). Python allows multiple base classes. It resolves methods using the method resolution order (MRO), a C3 linearisation you can print with Cls.__mro__, and super() means "the next class in the MRO", not "my parent". That makes small mixins (a class adding one capability, such as JsonMixin with to_json()) practical, as long as each one calls super().__init__(**kwargs) cooperatively. Mixins are still inheritance: keep them stateless and narrow.
In the interview
Messages go out by email, SMS or push. Some must also be logged, some retried up to three times, some both. A colleague proposes EmailNotifier, LoggedEmailNotifier, RetryingEmailNotifier, LoggedRetryingEmailNotifier, and the same for SMS and push. Propose a better design with Java and Python code.
Compare with our answer
Each channel is one class behind a Notifier interface; logging and retrying are wrappers that have a Notifier and are themselves Notifiers, so they stack in any order. This is composition, and the stacking wrappers are the Decorator pattern.
interface Notifier { void send(String to, String msg); }
class EmailNotifier implements Notifier {
public void send(String to, String msg) { System.out.println("email " + to + ": " + msg); }
}
class Logged implements Notifier {
private final Notifier inner;
Logged(Notifier inner) { this.inner = inner; }
public void send(String to, String msg) {
System.out.println("log: sending to " + to);
inner.send(to, msg);
}
}
class Retrying implements Notifier {
private final Notifier inner;
private final int attempts;
Retrying(Notifier inner, int attempts) { this.inner = inner; this.attempts = attempts; }
public void send(String to, String msg) {
for (int i = 1; ; i++) {
try { inner.send(to, msg); return; }
catch (RuntimeException e) { if (i >= attempts) throw e; }
}
}
}
Notifier n = new Logged(new Retrying(new EmailNotifier(), 3));class EmailNotifier:
def send(self, to: str, msg: str) -> None:
print(f"email {to}: {msg}")
class Logged:
def __init__(self, inner):
self.inner = inner
def send(self, to, msg):
print(f"log: sending to {to}")
self.inner.send(to, msg)
class Retrying:
def __init__(self, inner, attempts: int):
self.inner, self.attempts = inner, attempts
def send(self, to, msg):
for i in range(1, self.attempts + 1):
try:
return self.inner.send(to, msg)
except Exception:
if i == self.attempts:
raise
n = Logged(Retrying(EmailNotifier(), 3))A strong answer mentions: one Notifier interface · one class per channel · logging and retrying as wrappers that hold a Notifier · wrappers stacking in any order, so classes grow additively (3 channels + 2 features = 5 classes, not 12) · retries only being safe if sending twice is harmless (idempotency).
Your game has class Player extends Character and class Enemy extends Character. Now some enemies can be recruited and become the player's allies mid-game, keeping their health and inventory. What goes wrong, and how do you redesign?
Compare with our answer
An object can't change its class, so an Enemy can't become an ally without copying all its state into a new object (and every reference to the old one goes stale). "Enemy" is not what the character is, it is a role it has right now.
A strong answer mentions: an object cannot change class · modelling allegiance as a field or a part (Faction, or a Controller that is player-driven or AI-driven) · Character holding health and inventory once · swapping the part at run time · keeping inheritance only for real "is a" differences, if any remain.
- Inheritance = "is a", shares code and type; composition = "has a", delegates to parts; interface = "can do".
- Favour composition: features that vary independently, behaviour swapped at run time, code you don't own.
- Class explosion: n × m subclasses for combinations; composition needs n + m parts.
- Fragile base class: subclasses depend on the parent's implementation (the
HashSet.addAlldouble count). - Don't call overridable methods from constructors; keep fields private, not protected; keep hierarchies shallow.
- Inheritance is right for a stable "is a" with real shared behaviour, framework base classes, Template Method, sealed families.
- Design for inheritance or mark the class final.
- Composition's costs: forwarding boilerplate, more objects, the "self problem" with callbacks.
1. A coffee app has Coffee, MilkCoffee, SugarCoffee and MilkSugarCoffee subclasses. Oat milk, syrup and extra shots are coming next. What should you do?
Independent features multiply as subclasses. Holding add-ons as parts (or Decorator wrappers) grows linearly. Boolean flags avoid the explosion but scatter every add-on's logic through one class.
2. A class extends HashSet and overrides both add and addAll to count items. Adding three items with addAll reports 6. Why?
The inherited addAll is implemented with add, an internal detail the subclass now depends on. This is the fragile base class problem; wrapping a set instead avoids it.
3. Animal's constructor calls describe(). Dog overrides describe() to print its breed field, set in Dog's constructor. What is printed when you create a Dog?
The parent constructor runs first, but dynamic dispatch already calls Dog.describe(), which reads a field not yet assigned. Avoid overridable calls in constructors.
4. Which relationship is the best fit for inheritance?
A savings account is always an account and shares its rules. A car has an engine; a stack that extends a list exposes add(index) and breaks stack rules (Java's Stack extends Vector is the famous mistake); promotion changes a role, not a class.
5. In a game, characters can switch between walking, flying and swimming many times during one level. Which design handles this best?
Run-time change is composition's home ground: replace the part, keep the object and every reference to it. Replacing objects breaks references; throwing methods and string chains grow with every mode.
6. What is the main reason to mark a class final (or document it carefully) if it was not designed to be extended?
Subclasses couple themselves to self-use patterns inside the parent (the fragile base class). Either design and document for inheritance, or prevent it. The JIT can inline non-final methods anyway.
Score 60% or more and the lesson is marked complete.