Composition against inheritance

Lesson 048 showed extends as an is-a relation, and lesson 045 showed a class built from other objects. The two are not interchangeable, and the difference is not style: a subclass depends on how the superclass implements its methods, while a holding class depends only on what the held object promises. The program below is the famous demonstration of the first.

The fragile base class

A set that counts how many elements were added is a useful small class. The natural first attempt extends HashSet and overrides the two add methods:

import java.util.Collection; import java.util.HashSet; import java.util.Set; public class Fragile { public static void main(String[] args) { CountingSet<String> set = new CountingSet<>(); set.add("a"); set.addAll(Set.of("b", "c")); System.out.println("size " + set.size()); System.out.println("adds " + set.addCount); } } class CountingSet<E> extends HashSet<E> { int addCount; @Override public boolean add(E e) { addCount++; return super.add(e); } @Override public boolean addAll(Collection<? extends E> c) { addCount += c.size(); return super.addAll(c); } }

javac -Xlint:all Fragile.java
java Fragile

Fragile.java:13: warning: [serial] serializable class CountingSet has no definition of serialVersionUID
class CountingSet<E> extends HashSet<E> {
^
1 warning
size 3
adds 5

The set holds three elements and the counter says five, which is wrong by two. The warning above the output is the first sign that extending a collection brings obligations of its own: HashSet is Serializable, so the subclass owes a serialVersionUID.

Why the count is five

HashSet.addAll is implemented on top of its own add, one element at a time. The override of addAll adds two to the counter and then calls super.addAll, which calls add twice on the object of the subclass, so the overridden add runs twice as well. One call of addAll of two elements is counted three times.

Nothing in the subclass is wrong. The defect is the assumption that addAll does its own work; the superclass is free to reuse any of its methods, and its documentation is the only contract. A new JDK may change that implementation, and the subclass, unchanged, would count differently. That is a fragile base class: the base class can break its subclasses without changing its contract.

The same feature by composition

The class that holds a Set instead of being one cannot have that problem. Its addAll calls inner.addAll, which is the method of HashSet on a plain HashSet, so no override of the outer class runs:

import java.util.Collection; import java.util.HashSet; import java.util.Set; public class Composed { public static void main(String[] args) { CountingSet<String> set = new CountingSet<>(); set.add("a"); set.addAll(Set.of("b", "c")); System.out.println("size " + set.size()); System.out.println("adds " + set.addCount()); } } class CountingSet<E> { private final Set<E> inner = new HashSet<>(); private int addCount; boolean add(E e) { addCount++; return inner.add(e); } boolean addAll(Collection<? extends E> c) { addCount += c.size(); return inner.addAll(c); } int size() { return inner.size(); } int addCount() { return addCount; } }

javac -Xlint:all Composed.java
java Composed

size 3
adds 3

The count agrees with the size, the serial warning is gone because the class is not a collection, and the class no longer promises to be a Set. It offers the four methods its callers use, which is the whole job. The cost is that it is not a Set for a method that takes one; if that matters, the class implements Set and delegates every method, which the JDK itself does with Collections.unmodifiableSet.

When inheritance is right

Inheritance is right when the subclass really is a kind of the superclass and the superclass was designed for it: its methods are documented, its constructor is documented, and its self-use is part of the design. An abstract class with an abstract method is exactly that offer, because the subclass supplies a piece the superclass left open:

public class ShapesInherit { public static void main(String[] args) { Shape[] shapes = {new Circle(1), new Square(2)}; for (Shape shape : shapes) { System.out.printf("%s %.2f%n", shape.name(), shape.area()); } } } abstract class Shape { abstract double area(); String name() { return getClass().getSimpleName().toLowerCase(); } } class Circle extends Shape { private final double radius; Circle(double radius) { this.radius = radius; } @Override double area() { return Math.PI * radius * radius; } } class Square extends Shape { private final double side; Square(double side) { this.side = side; } @Override double area() { return side * side; } }

javac -Xlint:all ShapesInherit.java
java ShapesInherit

circle 3.14
square 4.00

The base class calls getClass and area on itself, and that is safe here because area is abstract on purpose and every subclass must supply it. The difference from HashSet is not the self-use but the design: one base class asked to be extended at that point, the other one merely happened to be extendable.

The refactor

The change from Fragile to Composed is mechanical: the extends becomes a field, every inherited method the class used becomes a one-line method that calls the field, and the count moves into the class because there is no longer a superclass to add to. The calls at the use site stay the same, which is why the refactor is worth doing late: the broken count is a bug report, not an interface change.

The rule of thumb the JDK documentation states: design for inheritance or forbid it. A class that offers neither an abstract method nor a documented contract is a class to hold, not to extend, and lesson 054 shows the final keyword that says so.

Exercises

  1. Call addAll with one element in Fragile and work out the count before you run it.
  2. Add a remove counter to Composed and delegate one more method.
  3. Make CountingSet implement Set and count the methods the compiler asks you to write.
  4. Explain why the serial warning in Fragile does not appear in Composed, in one sentence.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does the subclass count five adds for three elements?

    Answer

    HashSet.addAll calls add, and the overridden add counts again

    The base class reuses its own add, so the subclass override runs inside addAll as well.

  2. What is the fragile base class problem?

    Answer

    A change in how the base class implements a method can break a subclass without changing the contract

    The subclass depends on the implementation of the base class, not only on its documentation.

  3. What does composition depend on?

    Answer

    The methods of the held object, which are its contract

    A delegating class calls public methods and nothing else, so the implementation can change.

  4. What does this program print? public class Q1 { public static void main(String[] args) { B b = new B(); b.hello(); System.out.println(b.count); } } class A { void hello() { System.out.println("a"); } } class B extends A { int count; @Override void hello() { count++; super.hello(); } }

    Answer

    a then 1

    The override increments the counter once and calls the base method.

  5. What does this program print? public class Q2 { public static void main(String[] args) { Box box = new Box(new A()); box.hello(); System.out.println(box.calls); } } class A { void hello() { System.out.println("a"); } } class Box { private final A inner; int calls; Box(A inner) { this.inner = inner; } void hello() { calls++; inner.hello(); } }

    Answer

    a then 1

    The delegating method counts its own calls and forwards the call to the held object.

  6. What does this program print? public class Q3 { public static void main(String[] args) { Shape s = new Circle(2); System.out.printf("%.2f%n", s.area()); } } abstract class Shape { abstract double area(); } class Circle extends Shape { private final double r; Circle(double r) { this.r = r; } double area() { return 3 * r * r; } }

    Answer

    12.00

    The subclass supplies the abstract method and the call dispatches to it.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { Shape s = new Shape(); System.out.println(s.area()); } } abstract class Shape { abstract double area(); }

    Answer

    error: Shape is abstract; cannot be instantiated

    An abstract class has no complete implementation, so no object of it can exist.

  8. What does this program print? import java.util.ArrayList; import java.util.List; public class Q5 { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("a"); names.add("b"); System.out.println(names.size() + " " + names.get(1)); } }

    Answer

    2 b

    Composition at the use site: the code holds a List and calls its contract.

  9. Which is a sign that inheritance is the right choice?

    Answer

    The subclass is a kind of the superclass and the superclass documents how to extend it

    An is-a relation plus a base class designed for extension is what makes the coupling safe.

  10. What does final on a class say about inheritance?

    Answer

    It is not offered at all

    The class was not designed for extension, so the language forbids it.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev