Composition vs inheritance
Mid-level Frequently asked 4 min
On this page
The question
Why should you favor composition over inheritance?
30-second answer
Inheritance ties a subclass to how its parent is implemented, not just to what it promises. If the parent's methods call each other, an override can change behavior the parent relies on, and a parent update can break the subclass. Composition holds the other object as a field and uses only its public contract, so either side can change.
Understand it
A change request breaks inheritance
CompareCountingSet extends HashSet and counts in add(). Adding a, b and c one at a time counts 3, as it should.
View as text
A set that counts the elements added to it is built two ways: CountingSet extends HashSet, or CountingSet holds a Set and forwards to it. Three elements, a, b and c, are added.
Inheritance: CountingSet extends HashSet and counts in add(). Adding a, b and c one at a time counts 3, as it should. Marked Works.
Inheritance + addAll: the change request: count addAll() too. HashSet's inherited addAll() calls add() for each element, so every element is counted twice: 6. The calls list shows addAll adding 3, then three add calls each adding 1. Marked Fails.
Composition + addAll: CountingSet holds a Set and forwards to it. The inner set calls its own add(), not CountingSet's, so addAll() counts 3. Marked Works.
A set that counts the elements added to it is built two ways: CountingSet extends HashSet, or CountingSet holds a Set and forwards to it. Three elements, a, b and c, are added.
Inheritance: CountingSet extends HashSet and counts in add(). Adding a, b and c one at a time counts 3, as it should. Marked Works.
Inheritance + addAll: the change request: count addAll() too. HashSet's inherited addAll() calls add() for each element, so every element is counted twice: 6. The calls list shows addAll adding 3, then three add calls each adding 1. Marked Fails.
Composition + addAll: CountingSet holds a Set and forwards to it. The inner set calls its own add(), not CountingSet's, so addAll() counts 3. Marked Works.
Takeaway: A subclass depends on how its parent calls its own methods. Composition uses only the public contract, so the parent's internals cannot double-count.
In code
class CountingSet<E> {
private final Set<E> inner;
private int count;
CountingSet(Set<E> inner) { this.inner = inner; }
boolean add(E e) { count++; return inner.add(e); }
boolean addAll(Collection<? extends E> c) { count += c.size(); return inner.addAll(c); }
int count() { return count; }
}
// new CountingSet<String>(new HashSet<>()).addAll(List.of("a", "b", "c")) counts 3class InheritingCountingSet<E> extends HashSet<E> {
private int count;
@Override public boolean add(E e) { count++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
Wrong count += c.size(); return super.addAll(c); // HashSet's addAll calls add(): 3 elements count 6
}
int count() { return count; }
}interface Move { String step(); }
class Robot {
private Move move; // has-a
Robot(Move move) { this.move = move; }
void setMove(Move move) { this.move = move; }
String step() { return move.step(); }
}
Robot r = new Robot(() -> "walk");
r.setMove(() -> "fly"); // a WalkingRobot subclass could never become a flyerSolve it
Promote an engineer to manager without changing the object’s class
The HR model has Manager extends Employee and OnCallEngineer extends Employee. HR now needs to promote an engineer
while keeping their history, and some people are both team leads and on call. Redesign the model.
- Test the is-a. Inheritance says “always”. A promoted engineer was not always a manager, and an object cannot change its class, so promotion would mean a new object and lost history.
- Count the combinations. Lead and on call together would need
OnCallManager; every new role doubles the subclasses. - Compose instead. An
Employeehas a set ofRoleobjects. Each role brings its own behavior, such as approving leave or taking pages. - Check. Promotion adds a role; nothing is copied. Keep inheritance for a permanent is-a with a shared contract, such
as the
Roleimplementations themselves.
interface Role { String duty(); }
record ManagerRole(Team team) implements Role { public String duty() { return "approves leave for " + team.name(); } }
record OnCallRole(String rota) implements Role { public String duty() { return "answers pages on " + rota; } }
class Employee {
private final String name;
private final Set<Role> roles = new LinkedHashSet<>();
Employee(String name) { this.name = name; }
void grant(Role role) { roles.add(role); } // promotion: same object, same history
void revoke(Role role) { roles.remove(role); }
List<String> duties() { return roles.stream().map(Role::duty).toList(); }
}How to answer
- Inheritance is an is-a relationship and exposes the parent's whole API.
- A subclass depends on its parent's internals: the fragile base class problem.
- Composition is has-a: hold an object and forward to its public methods.
- Composition lets you swap the part at runtime and replace it with a fake in tests.
Common mistakes
- Saying inheritance is always wrong; it fits true is-a hierarchies designed for extension.
- Extending a class only to reuse a few of its methods.
Follow-up questions
What is the difference between an is-a and a has-a relationship?
Is-a is inheritance: a Circle is a Shape and can be used wherever a Shape is expected. Has-a is composition: a Car has an Engine as a field and uses it. Test is-a by substitution; if the subclass cannot stand in for the parent everywhere, the relationship is has-a.
- Is-a: extends or implements, and substitutable.
- Has-a: a field, used through its public methods.
- Failing substitution means has-a, not is-a.
See it in the infographic: A change request breaks inheritance
What is the fragile base class problem?
A subclass that relies on how its parent works can break when the parent changes, or behave wrongly already. A HashSet subclass that counts in both add() and addAll() counts 3 elements as 6, because HashSet's addAll() calls add().
- The parent's own methods can call your overrides.
- Those internal calls are rarely part of the documented contract.
- Composition avoids it, because the inner object never calls the wrapper.
class CountingSet<E> extends HashSet<E> {
int count;
@Override public boolean add(E e) { count++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
count += c.size();
return super.addAll(c);
}
}
// addAll(List.of("a", "b", "c")) leaves count at 6 See it in the infographic: A change request breaks inheritance
When is inheritance the right choice?
When the subclass truly is a kind of the parent and can replace it everywhere, and the parent was designed for extension: it documents which methods call which, and marks the rest final. Template methods and small sealed hierarchies of domain types are good fits.
- A true is-a relationship that passes substitution.
- A parent designed and documented for extension.
- Otherwise, make classes final and compose them.
See it in the infographic: A change request breaks inheritance
Why is Stack extends Vector considered a design mistake?
A stack is not a vector, but inheriting Vector gives Stack methods such as add(int, E) and get(int), so callers can insert or read anywhere and break last-in, first-out. The JDK (Java Development Kit) recommends a Deque, such as ArrayDeque, instead.
What does composition cost?
Forwarding: the wrapper must delegate every method it exposes, which is boilerplate. And the wrapped object does not know the wrapper, so calls it makes to itself skip the wrapper.
Check yourself
Show answers
- 3: Incorrect. addAll() counts 3, then each add() it calls counts again.
- 6: Correct. HashSet's addAll() calls the overridden add() once per element.
- 9: Incorrect. add() runs once per element, adding 3 more, not 6.
Show answers
- Car has an Engine field: Correct. A car has an engine; it is not one.
- Car extends Engine: Incorrect. A car is not an engine, and it would inherit every Engine method.
- Engine extends Car: Incorrect. An engine is not a kind of car.