Card 06/ 08

ComparisonDifficulty: Advanced1 min

Has-a Against Is-a: Composition or Inheritance

A class needs what another class already does. extends gets it in one word, and extends also exposes every method the parent has to every caller you will ever have.

java
class CountingList extends ArrayList<String> {
    int added = 0;
    @Override public boolean add(String s) { added++; return super.add(s); }
}
addAll may or may not call add, so the count may or may not be right
java
class CountingList {
    private final List<String> items = new ArrayList<>();
    private int added = 0;

    void add(String s) { added++; items.add(s); }
    int added() { return added; }
}
The two ways of reusing another class, on what each exposes and what each risks
Compared onInheritance — extendsComposition — a field
RelationshipThis is a thatThis has a that
Callers can useEvery public method of the parentOnly what you chose to expose
Breaks whenThe parent changes how its methods call each otherThe parent changes its behaviour
Swapping the implementationNot possible — the parent is fixedChange one field's type

The decision rule. Ask whether every method of the parent should be callable on your object, and whether your object could sensibly be handed to code expecting the parent. Two yeses mean inheritance. Anything less means a field.

The first listing shows why this is more than tidiness. A subclass depends on how the parent's methods call each other, which is an implementation detail the parent is free to change in a patch release.