Sub topic 14
Choose Inheritance or Composition
Why this choice matters
You now know how to build a subclass with extends, override methods, and call super. The next question is when to use these tools. Inheritance is one way to reuse code. It is not always the best way.
This chapter compares inheritance with a second technique called composition. You will learn a simple test for choosing between them. You will also see a real example where inheritance causes bugs and composition fixes them.
This chapter assumes you know classes, fields, constructors, and extends.
Two ways to reuse code
Inheritance means a class gets the members of another class by using extends. A Dog extends Animal, so a Dog is an Animal.
Composition means a class keeps another object in a field and uses it. A Car has an Engine. The Car calls methods on the engine when it needs them.
Both let you reuse work that already exists. They differ in how tightly the two classes are tied together.
| Question | Inheritance | Composition |
|---|---|---|
| Relationship | "is-a" | "has-a" |
| Keyword | `extends` | a field holding an object |
| Coupling | Tight. The subclass depends on the superclass internals. | Loose. The class depends only on the public methods of the other object. |
| Can change at runtime? | No. The superclass is fixed at compile time. | Yes. You can swap the object in the field. |
| Exposes all superclass methods? | Yes | No. You pick what to expose. |
The is-a and has-a test
Say the relationship out loud.
- A
Dogis anAnimal. This fits inheritance. - A
Caris anEngine. This sounds wrong, so do not use inheritance. - A
Carhas anEngine. This fits composition.
The test is a starting point, not a guarantee. A relationship can sound right and still be a poor use of inheritance, as the next example shows.
An example where inheritance goes wrong
Suppose you need a stack. A stack is a list where you add and remove items only at the top. Java already has ArrayList, so extending it looks like a quick win.
import java.util.ArrayList;
class BadStack extends ArrayList<String> {
void push(String item) {
add(item);
}
String pop() {
return remove(size() - 1);
}
}
public class BadStackDemo {
public static void main(String[] args) {
BadStack stack = new BadStack();
stack.push("a");
stack.push("b");
stack.add(0, "oops");
System.out.println(stack.pop());
System.out.println(stack);
}
}The program prints:
b
[oops, a]The code compiles and runs, but the design is broken. BadStack inherits every public method of ArrayList. Any caller can use add(0, "oops") to insert at the bottom, or remove(0) to take from the bottom. A stack should not allow that. A subclass cannot hide inherited public methods. It inherits all of them.
The words "a stack is a list" also fail the test in a deeper way. A list lets you work anywhere. A stack promises that you work only at the top. A stack is not a list in the sense that matters for substitution, because code that expects a list could break a stack's promise.
The same idea with composition
With composition, the stack keeps a list in a private field. Only the methods you write are public.
import java.util.ArrayList;
import java.util.List;
class SimpleStack {
private final List<String> items = new ArrayList<>();
void push(String item) {
items.add(item);
}
String pop() {
return items.remove(items.size() - 1);
}
int size() {
return items.size();
}
boolean isEmpty() {
return items.isEmpty();
}
}
public class SimpleStackDemo {
public static void main(String[] args) {
SimpleStack stack = new SimpleStack();
stack.push("a");
stack.push("b");
System.out.println(stack.pop());
System.out.println(stack.size());
}
}The program prints:
b
1Now a caller cannot call add(0, ...), because SimpleStack has no such method. The ArrayList is an internal detail. You could replace it with a LinkedList later, and no caller would notice.
Passing a call along to the inner object is called delegation. Each method in SimpleStack delegates to items.
The fragile base class problem
Inheritance has a second risk. A subclass depends on how the superclass works inside, not only on what it promises. If the superclass changes internally, the subclass can break even though its own code did not change. This is the fragile base class problem.
Here is an example. You want a set that counts how many items were added. You extend HashSet and override both add and addAll.
import java.util.Arrays;
import java.util.HashSet;
class CountingSet extends HashSet<String> {
private int addCount = 0;
@Override
public boolean add(String item) {
addCount++;
return super.add(item);
}
@Override
public boolean addAll(java.util.Collection<? extends String> items) {
addCount += items.size();
return super.addAll(items);
}
int getAddCount() {
return addCount;
}
}
public class CountingSetDemo {
public static void main(String[] args) {
CountingSet set = new CountingSet();
set.addAll(Arrays.asList("x", "y", "z"));
System.out.println(set.getAddCount());
}
}You expect 3. On common JDK versions the program prints 6.
The reason is that the inherited addAll method calls add for each item. Your overridden add runs three times and counts three. Your overridden addAll already counted three. The total is six.
You could "fix" this by removing the count in addAll. That fix depends on a detail the HashSet documentation does not promise. A future JDK could change it, and your count would break again.
Composition avoids the problem. The wrapper does not inherit anything, so no hidden call can reach your code.
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
class CountingSetFixed {
private final Set<String> set = new HashSet<>();
private int addCount = 0;
boolean add(String item) {
addCount++;
return set.add(item);
}
boolean addAll(Collection<? extends String> items) {
addCount += items.size();
return set.addAll(items);
}
int getAddCount() {
return addCount;
}
}
public class CountingSetFixedDemo {
public static void main(String[] args) {
CountingSetFixed set = new CountingSetFixed();
set.addAll(Arrays.asList("x", "y", "z"));
System.out.println(set.getAddCount());
}
}This program prints 3, and it keeps printing 3 no matter how HashSet is written inside.
When inheritance is the right choice
Inheritance is still useful. It works well when all of these are true:
- The relationship is truly "is-a", and it stays true in every situation. A
Dogis always anAnimal. - Any code that works with the superclass also works correctly with the subclass. This idea is called substitutability.
- You control both classes, or the superclass was designed to be extended and says so in its documentation.
- You want polymorphism, meaning one variable of the superclass type can hold many kinds of objects, as in
Animal animal = new Dog("Rex");.
Abstract classes are a good fit. An abstract Shape with a method area() and concrete subclasses Circle and Square is a clear "is-a" design. The superclass is meant to be extended.
Composition with interfaces
You can get polymorphism without inheriting from a class. Define an interface, and let several classes implement it. A class can then hold a field of the interface type and delegate to it.
interface Engine {
String start();
}
class PetrolEngine implements Engine {
public String start() {
return "Petrol engine running";
}
}
class ElectricEngine implements Engine {
public String start() {
return "Electric motor humming";
}
}
class Car {
private final Engine engine;
Car(Engine engine) {
this.engine = engine;
}
String drive() {
return engine.start();
}
}
public class CarDemo {
public static void main(String[] args) {
Car petrolCar = new Car(new PetrolEngine());
Car electricCar = new Car(new ElectricEngine());
System.out.println(petrolCar.drive());
System.out.println(electricCar.drive());
}
}The program prints:
Petrol engine running
Electric motor hummingCar is not tied to one engine type. You choose the engine when you create the car. Inheritance cannot do this, because a subclass picks its superclass once, in the source code.
A decision guide
The flowchart summarizes the questions to ask. When unsure, follow it to the end.
Many programmers follow the rule "prefer composition over inheritance". It does not mean inheritance is bad. It means you should start with composition and choose inheritance only when the questions above all get a "yes".
Common mistakes
- Extending a class only to reuse a few methods. If the relationship is not "is-a", hold an object in a field instead.
- Extending a utility class such as
ArrayListorHashSet. These classes were not designed for your subclass, and you inherit methods you do not want. - Forgetting that a subclass inherits all public methods. You cannot remove them, so the subclass must support every one.
- Building deep chains of classes. A hierarchy with many levels is hard to read, because behavior may come from any level. Keep hierarchies shallow.
- Using
finaltoo late. If a class was not designed for extension, mark itfinalso that nobody extends it by accident.
Summary
- Inheritance models "is-a". Composition models "has-a".
- Inheritance ties a subclass to the internal behavior of its superclass. Composition ties a class only to the public methods of another object.
- A subclass inherits every public method and cannot hide them, so a poor "is-a" choice exposes operations you do not want.
- Overriding methods in a class you do not control can break when the superclass changes.
- Use inheritance when the relationship is permanent, substitutable, and the superclass is meant to be extended. Otherwise, use composition, often with an interface.
Exercise
A programmer writes class Printer extends ArrayList<String> so that Printer can store a list of lines to print. Give two reasons this design is risky, and describe how to rewrite it with composition.
Show answer
First, a printer is not a kind of list, so the "is-a" test fails. Second, Printer inherits every public ArrayList method, so callers can insert, remove, or reorder lines in ways a printer should not allow. The class also depends on ArrayList internals. To rewrite it, give Printer a private final List<String> lines = new ArrayList<>(); field. Add only the public methods the printer needs, such as addLine(String) and print(), and have them delegate to lines.
Exercise
In the CountingSet example, addAll was overridden and the count came out as 6 instead of 3. Explain in one or two sentences why the count is too high.
Show answer
The inherited HashSet addAll calls add once for each item. Because add is overridden, each of those calls increases the count again, on top of the increase already made in the overridden addAll. Three items are counted twice, giving 6.
Exercise
Decide for each pair whether inheritance or composition fits best, and explain with the is-a or has-a test: (a) Circle and Shape, (b) Library and Book, (c) Student and Address.
Show answer
(a) Inheritance fits. A circle is a shape, and code that expects a shape works with a circle. (b) Composition fits. A library has books, and a library is not a kind of book. (c) Composition fits. A student has an address, and a student is not a kind of address.