JAVA-270 · Lesson 6 of 12 · 21 min
Composition over inheritance
▶ Video coming soon A video version of this lesson is on the way.
Tuesday, February 15, 2028. Hamza has found a bug that took him a whole Sunday. CounterApp keeps a count of how many parts are added to each order, using a class he wrote in 2027 called CountingOrder that extends ArrayList and adds one to a counter whenever an item is added. For one order the count said 6 when the order had 3 items. Ingrid smiles, because the bug is famous: it is almost exactly the example Joshua Bloch uses in Effective Java to explain why you should favor composition over inheritance. Tonight is about that advice, which the Gang of Four put on page 20 of their book, years before Bloch's example: favor object composition over class inheritance.
Two ways to reuse code
Object-oriented languages give two main ways to build a class from existing code. Inheritance makes a new class a subclass of an existing one with extends: the subclass gets all the parent's fields and methods and can override some of them. Composition gives the new class a field holding an object of the existing class, and the new class calls that object to do part of its work. Inheritance says a cargo bike is a bike. Composition says a cargo bike has a cargo box.
Both are useful, and Java needs both. The trouble is that inheritance is often used where composition would be safer, because extends looks like the quickest way to reuse code. The cost shows up later, in subclasses that break when the parent changes, and in hierarchies that multiply into dozens of classes.
| Inheritance (extends) | Composition (a field) | |
|---|---|---|
| Relationship | Is a | Has a, or uses a |
| Coupling to the reused class | Tight: the subclass depends on how the parent works inside | Loose: the class depends only on the other object's public methods |
| Chosen when | At compile time, fixed forever | At run time; the object in the field can be swapped |
| Exposes | Every public method of the parent | Only the methods the class chooses to offer |
| Risk | Fragile base class, class explosion | A little more forwarding code |
The fragile base class
Here is a simplified version of Hamza's bug. CountingOrder extends ArrayList and overrides both add and addAll to count the items added.
import java.util.*;
public class Main {
static class CountingOrder extends ArrayList<String> {
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);
}
}
public static void main(String[] args) {
CountingOrder order = new CountingOrder();
order.addAll(List.of("TUBE-700x25", "BELL", "PAD-ROAD"));
System.out.println("items in order: " + order.size());
System.out.println("items counted: " + order.added);
}
}items in order: 3 items counted: 3
What this code does
CountingOrder looks correct: add counts one item and addAll counts a whole collection. But it reports 3 items in the order and 3 counted only because ArrayList's addAll happens not to call add internally. The subclass's correctness depends on a detail of how the parent is written, which the parent never promised to keep.
In this JDK, ArrayList.addAll copies the array directly and the count is right. Bloch's original example used HashSet, whose addAll is inherited from AbstractCollection and does call add for each element, so the same subclass counts every item twice, reporting 6 for 3 items, which is exactly what Hamza saw: in 2027 CounterApp's order class extended a LinkedHashSet.
import java.util.*;
public class Main {
static class CountingOrder extends LinkedHashSet<String> {
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);
}
}
public static void main(String[] args) {
CountingOrder order = new CountingOrder();
order.addAll(List.of("TUBE-700x25", "BELL", "PAD-ROAD"));
System.out.println("items in order: " + order.size());
System.out.println("items counted: " + order.added);
}
}items in order: 3 items counted: 6
What this code does
The same counting subclass, now extending LinkedHashSet, reports 6 items counted for an order of 3. LinkedHashSet inherits an addAll that calls add once for each element, so every item is counted once in addAll and again in the overridden add. Nothing in the subclass changed; a hidden detail of the parent decided whether it worked.
This is the fragile base class problem: a subclass depends on implementation details of its parent, so a change to the parent, or a choice of a different parent, can break the subclass without any change to the subclass itself. The parent's authors cannot know which details their subclasses rely on, and the subclass authors cannot see the details without reading the parent's source. Inheritance breaks encapsulation in exactly the way lesson 1 warned against.
The fix: wrap instead of extend
The composition version holds the set in a private field and forwards calls to it. It decides exactly which methods to offer, and its counting no longer depends on how the set is written inside, because the set never calls back into it.
import java.util.*;
public class Main {
static final class CountingOrder {
private final Set<String> items = new LinkedHashSet<>();
private int added = 0;
boolean add(String item) {
added++;
return items.add(item);
}
void addAll(Collection<String> more) {
for (String item : more) add(item);
}
int size() { return items.size(); }
int added() { return added; }
List<String> items() { return List.copyOf(items); }
}
public static void main(String[] args) {
CountingOrder order = new CountingOrder();
order.addAll(List.of("TUBE-700x25", "BELL", "PAD-ROAD"));
order.add("BELL");
System.out.println("items in order: " + order.size() + " " + order.items());
System.out.println("items counted: " + order.added());
}
}items in order: 3 [TUBE-700x25, BELL, PAD-ROAD] items counted: 4
What this code does
CountingOrder now has a set instead of being one, and every operation goes through its own methods. addAll is written in terms of the class's own add, so each item is counted exactly once whatever the set does internally; the second BELL is counted as an attempt but not stored twice. The class offers only the operations an order needs, and items returns a copy so callers cannot change the set behind its back.
A class written this way, which wraps an object and forwards calls to it, is sometimes called a forwarding class or a wrapper; it is the decorator pattern from lesson 4. It is a little more code than extends, because each method you want must be written out. In return the class is immune to changes in the wrapped object's internals, and it can hold any implementation of the interface, not just the one it was written against.
Class explosion
The second problem with inheritance appears when variations combine. In 2027 CounterApp had a class for each kind of rental bike, then needed variations for bikes with child seats, bikes with cargo boxes and bikes with electric assist. With inheritance, every combination needs its own subclass: CitySeatBike, CargoAssistBike, CitySeatAssistBike and so on. Three types and three optional features already allow 3 × 2 × 2 × 2 = 24 combinations.
With composition, a bike has a type and a set of accessories, and each accessory is a small object that knows its own extra price. New accessories are new classes; no combination ever needs a class of its own.
import java.util.*;
public class Main {
enum Type {
CITY(2500), CARGO(4000), TANDEM(4500);
final int perDay;
Type(int perDay) { this.perDay = perDay; }
}
interface Accessory { String name(); int perDay(); }
record ChildSeat() implements Accessory { public String name() { return "child seat"; } public int perDay() { return 300; } }
record CargoBox() implements Accessory { public String name() { return "cargo box"; } public int perDay() { return 500; } }
record Assist() implements Accessory { public String name() { return "electric assist"; } public int perDay() { return 1500; } }
record RentalBike(String id, Type type, List<Accessory> extras) {
int perDay() { return type.perDay + extras.stream().mapToInt(Accessory::perDay).sum(); }
String describe() {
return id + " (" + type + (extras.isEmpty() ? "" : " + " + extras.stream().map(Accessory::name).toList()) + ") " + perDay();
}
}
public static void main(String[] args) {
List<RentalBike> fleet = List.of(
new RentalBike("CITY-1", Type.CITY, List.of()),
new RentalBike("CITY-2", Type.CITY, List.of(new ChildSeat())),
new RentalBike("CARGO-1", Type.CARGO, List.of(new CargoBox(), new Assist())));
for (RentalBike b : fleet) System.out.println(b.describe());
System.out.println("possible combinations without new classes: " + Type.values().length * 2 * 2 * 2);
}
}CITY-1 (CITY) 2500 CITY-2 (CITY + [child seat]) 2800 CARGO-1 (CARGO + [cargo box, electric assist]) 6000 possible combinations without new classes: 24
What this code does
A RentalBike has a type, held in an enum, and a list of accessories, each a small record with its own daily price. Any combination is just a different list, so the three types and three accessories cover 24 combinations with five small types instead of 24 subclasses. Adding a new accessory, such as a rain cover, is one new record.
Delegation and interface default methods
Composition often uses delegation: an object receives a request and hands it to another object it holds, possibly adding something of its own. Delegation gives most of the code reuse people want from inheritance, without tying the two classes together.
Java's interfaces can also carry behavior. A default method in an interface has a body, and every class that implements the interface gets it unless it overrides it. Default methods let you share small pieces of behavior across unrelated classes without a common parent class, because a class can implement many interfaces but extend only one class.
import java.util.*;
public class Main {
interface Priced {
int cents();
default int withTax(int inHundred) { return cents() + Math.round(cents() * inHundred / 100.0f); }
default String price() { return cents() / 100 + "." + String.format("%02d", cents() % 100); }
}
record Part(String code, int cents) implements Priced {}
record Repair(String kind, int minutes) implements Priced {
public int cents() { return minutes * 6500 / 60; }
}
static final class Invoice implements Priced {
private final List<Priced> lines = new ArrayList<>();
Invoice add(Priced p) { lines.add(p); return this; }
public int cents() { return lines.stream().mapToInt(Priced::cents).sum(); }
}
public static void main(String[] args) {
Invoice inv = new Invoice().add(new Part("TUBE-700x25", 899)).add(new Repair("FLAT", 15));
System.out.println("tube: " + new Part("TUBE-700x25", 899).price());
System.out.println("flat repair: " + new Repair("FLAT", 15).price());
System.out.println("invoice: " + inv.price() + ", with 13 in 100 tax: " + inv.withTax(13));
}
}tube: 8.99 flat repair: 16.25 invoice: 25.24, with 13 in 100 tax: 2852
What this code does
Priced declares one abstract method, cents, and two default methods built on it, so any class that can state a price in cents also gets formatting and tax for free. A part, a repair and a whole invoice share this behavior without sharing a parent class. The invoice delegates to its lines to add up its own price.
Default methods should stay small and built only on the interface's own abstract methods. An interface cannot hold instance fields, so default methods cannot keep state, which is a useful limit: it keeps interfaces from turning back into the base classes this lesson warns about.
When inheritance is the right tool
Composition over inheritance is a preference, not a ban. Inheritance is right when the subclass really is a special kind of the parent, will keep every promise the parent makes, which is the Liskov rule from lesson 2, and when the parent was designed to be extended. Bloch puts it as a rule for the parent's authors: design and document for inheritance, or else prohibit it. Making a class final, or using records, which are always final, prohibits it.
Modern Java offers a controlled middle way. A sealed class or interface lists exactly which subtypes may exist, so a hierarchy cannot be extended by surprise. Abstract classes designed as templates, as in lesson 5's Report, are another safe use: the parent fixes the algorithm in a final method and documents exactly which methods subclasses fill in.
| Use inheritance when | Use composition when |
|---|---|
| The subtype is a true special case and keeps every promise | You want to reuse behavior but the types are not really the same kind |
| The parent was designed and documented for extension | The class you want to reuse was not designed for it, such as a library collection |
| The set of subtypes is closed, ideally sealed | Variations combine, so subclasses would multiply |
| A template method fixes the algorithm and subclasses fill steps | You want to swap the behavior at run time or in tests |
Try it yourself
Wrap the list instead of extending it
The starter's Basket extends ArrayList, so callers can call clear and remove on it, which the shop does not allow. Rewrite Basket to hold a private List<String> and offer only add, size and contents (which returns List.copyOf). Keep main working.
The program should print basket: [BELL, LOCK] and size: 2.
import java.util.*;
public class Main {
static class Basket extends ArrayList<String> {}
public static void main(String[] args) {
Basket b = new Basket();
b.add("BELL");
b.add("LOCK");
b.add("PUMP-FLOOR");
b.remove("PUMP-FLOOR");
System.out.println("basket: " + b);
System.out.println("size: " + b.size() + " (remove was allowed)");
}
}Try it yourself
Compose a discount into a price
The starter has a MemberRepair subclass that overrides price. Replace the subclass with composition: give Repair a field of type IntUnaryOperator called discount, use it in price, and create a member repair with c -> c - c / 10 and a regular one with c -> c.
The program should print regular: 6500 and member: 5850.
public class Main {
static class Repair {
int price() { return 6500; }
}
static class MemberRepair extends Repair {
@Override int price() { return super.price() - 600; }
}
public static void main(String[] args) {
System.out.println("regular: " + new Repair().price());
System.out.println("member: " + new MemberRepair().price());
}
}Common mistakes
MistakeExtending a library class to add a small feature.
InsteadWrap it in a class that holds it in a field and forwards the calls you need.
MistakeRelying on how a parent class calls its own methods.
InsteadDo not depend on undocumented details; composition avoids the callbacks entirely.
MistakeA subclass for every combination of features.
InsteadCompose: give the object a list or set of feature objects.
MistakeLeaving classes open to extension by accident.
InsteadMake classes final or sealed unless they are designed and documented for inheritance.
MistakePutting state-heavy logic in interface default methods.
InsteadKeep default methods small and built on the interface's abstract methods.
Summary and key terms
- Inheritance makes a class a subclass of another and reuses its code; composition gives a class a field holding another object and delegates to it.
- Inheritance couples a subclass to its parent's implementation details, which causes the fragile base class problem: a subclass can break when the parent changes, or when a different parent is chosen, as the counting set showed.
- A forwarding class that wraps an object and calls only its public methods is immune to those details.
- When variations combine, subclasses multiply, while composition handles combinations with lists of small objects.
- Delegation and interface default methods share behavior without a common parent class.
- Inheritance remains right for true is-a relationships whose subtypes keep every promise, for classes designed and documented for extension, and for closed hierarchies marked sealed.
- Classes not designed for inheritance should be final.
- Inheritance
- Building a class as a subclass of another with extends, reusing and overriding its methods.
- Composition
- Building a class that holds other objects in fields and uses them to do its work.
- Is-a relationship
- A relationship in which one type is a special kind of another.
- Has-a relationship
- A relationship in which one object contains or uses another.
- Fragile base class problem
- A subclass breaking because of a change to the implementation of its parent.
- Self-use
- A class calling its own overridable methods internally, which subclasses can disturb.
- Forwarding class
- A wrapper that passes calls on to an object it holds.
- Delegation
- Handing a request to another object to carry out.
- Class explosion
- The rapid growth in subclasses when variations are combined through inheritance.
- Default method
- An interface method with a body that implementing classes inherit unless they override it.
- Sealed class
- A class or interface that lists exactly which subtypes may extend or implement it.
- Final class
- A class that cannot be extended.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why did the counting set report 6 for 3 items?
Show answer
LinkedHashSet's inherited addAll calls add for each element, so each item was counted in addAll and again in add.
Why does the composition version count correctly whatever set it holds?
Show answer
The set never calls back into CountingOrder; addAll is written using the class's own add.
How many classes would inheritance need for 3 bike types with any of 3 optional accessories?
Show answer
24, one per combination; composition needs the types and one class per accessory.
Can an interface default method keep a running total in a field?
Show answer
No; interfaces cannot have instance fields.
What does Bloch say about classes and inheritance?
Show answer
Design and document a class for inheritance, or else prohibit it.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.