Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Why does Effective Java advise favouring composition over inheritance? Explain with the InstrumentedHashSet example and show the composed version.

A HashSet subclass that counts additions by overriding both add and addAll counts every element twice when addAll is used, because HashSet's addAll, inherited from AbstractCollection, calls add for each element internally. The subclass silently depends on that undocumented self-use, which could change in any release. The composed version is a forwarding class that implements Set, holds a Set field and delegates to it, so it counts in its own methods, works with any Set implementation and is unaffected by the wrapped set's internals; inheritance remains right only for true is-a relationships with parents designed and documented for extension.

Why this question is asked

Favour composition over inheritance is one of the best known pieces of advice in Java design, and Effective Java illustrates it with a set that counts how many elements were added. The example is worth knowing in detail because it shows the problem concretely: a subclass that looks perfectly correct gives the wrong answer because of how its parent is written inside. Interviewers ask for it to see whether we understand why inheritance is fragile and can write the composed alternative from memory. In this answer, we will write the inheriting version, see it double count and explain why, build the forwarding version, and then discuss when inheritance is still the right tool. The code below is our own; only the idea comes from the book.

1A Quick Recap: Inheritance Versus Composition

With inheritance, a class extends another and gets all its methods; it can override some of them. With composition, a class holds a reference to another object in a field and calls it to do work; when it simply passes calls on, this is called forwarding or delegation. Both reuse code, but inheritance also inherits the parent's internal behaviour, including which of its own methods it calls and when, something called self-use. Composition only sees the other object's public contract.

2The Inheriting Version and Its Surprising Result

We want a set that tracks how many elements were ever added, including duplicates that were attempted. Extending HashSet and overriding the two adding methods looks like the obvious solution.

Java
class InstrumentedHashSet<E> extends HashSet<E> {
private int addCount = 0;
@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);
}
public int getAddCount() { return addCount; }
}
var s = new InstrumentedHashSet<String>();
s.addAll(List.of("a", "b", "c"));
System.out.println(s.getAddCount()); // 6, not 3
Step throughWhy addAll counts twice
CallerInstrumentedHashSetHashSet / AbstractCollection
addAll([a, b, c]): addCount = 3
super.addAll(c)
this.add(a): overridden, addCount = 4
this.add(b): addCount = 5
this.add(c): addCount = 6
getAddCount() returns 6

6 messages in order. Play them, or step through them one at a time.

The parent's addAll calls add on this, which is our override.

Notice that each method looks correct on its own. addAll adds the size of the collection, three, and then calls the parent. The problem is what the parent does next.

3Why It Double Counts

HashSet does not declare its own addAll; it inherits it from AbstractCollection, and that implementation loops over the collection and calls add(e) for each element. Inside the parent, add means this.add, and this is our InstrumentedHashSet, so dynamic dispatch runs our overridden add, which increments the counter again. Each element is counted once in our addAll and once more in our add.

We could 'fix' it by removing our addAll override and relying on the parent to call add. The count would then be correct, but only because of a detail that is not part of HashSet's contract. If a future release, or another Set implementation we later switch to, implemented addAll without calling add, for speed for example, our counter would silently undercount. This is the core of the argument: a subclass that overrides methods depends on the parent's self-use, which is an implementation detail, so the subclass can break whenever the parent changes even if no public method changes. Adding a new adding method to the parent in a later version, which our subclass does not override, would let elements in without being counted at all.

4The Composed Version: A Forwarding Set

Instead of being a HashSet, our class has a Set. We split it into two parts: a reusable forwarding class that implements Set and passes every call to a wrapped set, and the instrumented class that extends the forwarding class and adds counting.

Java
class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
ForwardingSet(Set<E> s) { this.s = s; }
public boolean add(E e) { return s.add(e); }
public boolean addAll(Collection<? extends E> c) { return s.addAll(c); }
public int size() { return s.size(); }
public boolean contains(Object o) { return s.contains(o); }
public Iterator<E> iterator() { return s.iterator(); }
// ... every other Set method forwards to s the same way
@Override public boolean equals(Object o) { return s.equals(o); }
@Override public int hashCode() { return s.hashCode(); }
@Override public String toString() { return s.toString(); }
}
class InstrumentedSet<E> extends ForwardingSet<E> {
private int addCount = 0;
InstrumentedSet(Set<E> s) { super(s); }
@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); }
public int getAddCount() { return addCount; }
}
var s = new InstrumentedSet<>(new HashSet<String>());
s.addAll(List.of("a", "b", "c"));
System.out.println(s.getAddCount()); // 3

Now addAll forwards to the wrapped HashSet's addAll. Inside the HashSet, add means the HashSet's own add, not ours, because the HashSet knows nothing about the wrapper. Our counter is touched only by our two methods, so the count is exactly three. Notice that InstrumentedSet still extends something, ForwardingSet, but that is safe: ForwardingSet is ours, it is designed for extension, and it has no self-use at all, every method just forwards.

5What the Wrapper Gains

Because the wrapper depends only on the Set interface, it works with any implementation: new InstrumentedSet<>(new TreeSet<>()) counts additions to a sorted set, and new InstrumentedSet<>(ConcurrentHashMap.newKeySet()) to a concurrent one. The inheriting version would need a separate subclass for each. And the wrapper is immune to changes in the wrapped set's internals, because it never relies on how one of its methods is implemented in terms of another. This pattern, adding behaviour by wrapping an object with the same interface, is the decorator pattern, and the JDK uses it widely, for example BufferedInputStream wrapping any InputStream and Collections.unmodifiableSet wrapping any Set.

Inheriting versus forwarding
Propertyextends HashSetwraps a Set
addAll of 3 elementscounts 6counts 3
Depends on parent's self-useyesno
Works with TreeSet, concurrent setsno, one subclass eachyes, any Set
Breaks if the parent changes internalspossiblyno
Extra codenonea forwarding class, written once

6When Inheritance Is Still Right

Inheritance is appropriate when there is a true is-a relationship, every instance of the subclass really is an instance of the parent in every context, and when the parent is designed and documented for extension: it says which methods call which, offers specific protected hooks, and its authors treat that as part of the contract. AbstractList is a JDK example; its documentation tells implementers exactly which methods to provide. Inheritance within one package or one team, where the same people own parent and child, is also much safer than across library boundaries. Otherwise, a forwarding wrapper costs a little boilerplate and buys independence from someone else's internals.

7Follow-up questions

Does the wrapper have any drawbacks?

A few. It needs boilerplate to forward every method, though IDEs generate it. It does not suit callback frameworks where the wrapped object passes a reference to itself to someone else, because those callbacks then bypass the wrapper; this is sometimes called the SELF problem. And identity changes: the wrapper is a different object from the set it wraps, so code that compares references sees two objects. In most business code none of these matter.

Why delegate equals and hashCode in ForwardingSet?

Set's contract defines equality as having the same elements, and other sets compare with us through equals. Forwarding equals and hashCode to the wrapped set keeps the wrapper consistent with that contract, so an InstrumentedSet holding a, b and c equals any other set holding them.

8Conclusion

In this answer, we saw that a HashSet subclass overriding add and addAll counts addAll elements twice, because the inherited addAll calls add on this, which is the override. The subclass depends on the parent's undocumented self-use, so even a fix that happens to work can break in a later release. The composed version, a ForwardingSet that implements Set and delegates to a wrapped set, plus an InstrumentedSet that counts in its own methods, gave the right count, works with any Set implementation and ignores the wrapped set's internals. Inheritance stays the right choice for true is-a relationships with parents designed and documented for extension.

What to say in the interviewAbout 90 seconds aloud

Open with

The example is a set that counts how many elements were added. If I extend HashSet and override add and addAll, both incrementing a counter, then adding three elements with addAll gives a count of six.

Then, if they want more

The reason is that HashSet inherits addAll from AbstractCollection, which simply calls add for each element, and because of dynamic dispatch that call goes to my overridden add, so every element is counted twice.

I could remove my addAll override, but then correctness depends on an undocumented implementation detail, the parent's self-use, which could change in any release, and if the parent added a new insertion method, my subclass would miss it. That is the fragility of inheritance: the subclass depends on the parent's internals, not just its contract.

The composed version is a forwarding class that implements Set and holds a private Set field, delegating every method to it. My InstrumentedSet extends that forwarding class and counts in add and addAll before delegating. Now the wrapped HashSet's addAll calls its own add, not mine, so the count is three.

As a bonus, the wrapper works with any Set, a TreeSet or a concurrent set, and is unaffected by their internals; it is the decorator pattern. I still use inheritance when there is a real is-a relationship and the parent is designed and documented for extension, like AbstractList.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why does Effective Java advise favouring composition over inheritance? Explain with the...": https://scrivio-interview-library.netlify.app/java/oop-principles/ebc3794589/