Card 06/ 08
All 8 cards
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.
class CountingList extends ArrayList<String> {
int added = 0;
@Override public boolean add(String s) { added++; return super.add(s); }
}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; }
}| Compared on | Inheritance — extends | Composition — a field |
|---|---|---|
| Relationship | This is a that | This has a that |
| Callers can use | Every public method of the parent | Only what you chose to expose |
| Breaks when | The parent changes how its methods call each other | The parent changes its behaviour |
| Swapping the implementation | Not possible — the parent is fixed | Change 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.