Quick revision
The short answer
HashSet inherits addAll from AbstractCollection, and that addAll simply calls add() once per element. When our subclass counts in both addAll and add, each element is counted once in addAll and again in the overridden add, so three elements give a count of six. The subclass broke because it relied on an undocumented detail of its parent, which could change again in any release. Composition fixes it: a wrapper class implements Set, forwards every call to a private Set, and does its counting only in its own methods, so the parent's internals no longer matter.
What to remember
In this answer, we saw that InstrumentedHashSet counts each element twice because HashSet's inherited addAll calls the overridden add() on this. The subclass depends on that undocumented self-use, which could change in any release, and new parent methods could bypass the count. Composition removes the dependency: a forwarding wrapper implements Set, delegates to a private Set and counts only in its own methods. Classes that are meant to be extended must document their self-use; the rest should be final.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
HashSet inherits addAll from AbstractCollection, and that addAll simply calls add() once per element. When our subclass counts in both addAll and add, each element is counted once in addAll and again in the overridden add, so three elements give a count of six. The subclass broke because it relied on an undocumented detail of its parent, which could change again in any release. Composition fixes it: a wrapper class implements Set, forwards every call to a private Set, and does its counting only in its own methods, so the parent's internals no longer matter.
Why this question is asked
Inheritance looks like the natural way to add a little behaviour to an existing class, and this example shows how it goes wrong even in a tiny class with two methods. The same trap appears in real Spring code when we extend a framework class, such as a template or a base controller, and override a method that the parent also calls internally. Interviewers ask about it because explaining the double count requires understanding dynamic dispatch and the idea of a fragile base class. In this answer, we will reproduce the double count, trace the calls to see where the second count comes from, understand why this makes the subclass fragile, fix it with composition, and finish with the rule for designing classes that may be extended.
1Reproducing the Double Count
The goal is a set that remembers how many elements anyone has tried to add, including duplicates. The obvious approach is to extend HashSet and override both ways of adding.
The code looks correct when we read each method on its own. addAll adds the size of the collection, add adds one. Yet three elements give a count of six.
2Tracing Where the Second Count Comes From
HashSet does not define its own addAll. It inherits the one from AbstractCollection, which loops over the collection and calls add(e) for each element. That call is a normal virtual call on this, and this is our InstrumentedHashSet object. Java's dynamic dispatch, choosing the method by the runtime type of the object, sends each of those calls to our overridden add(), which increments the counter again.
So our addAll adds 3, then super.addAll() calls our add() three times, and each adds 1. Total: 6. This pattern, a class calling its own overridable methods, is called self-use.
6 messages in order. Play them, or step through them one at a time.
The parent's addAll calls add() on this, so dynamic dispatch reaches our override.
3Why the Subclass Is Fragile
We could 'fix' it by not overriding addAll at all, and the count would come out right today. But that fix is worse than it looks, because it works only because AbstractCollection.addAll happens to call add(). Whether it does is an implementation detail, not something the HashSet documentation promises. A future JDK could implement addAll differently, for example by inserting elements directly for speed, and our count would silently drop to zero for bulk adds.
There is a second risk. If a later version of the parent adds a new method that inserts elements, our subclass does not override it, so elements added through it are never counted. The subclass is coupled to the parent's internals in both directions. This is the fragile base class problem: correct-looking changes in a superclass break subclasses that its authors have never seen. Inheritance breaks encapsulation because the subclass depends on how the parent is implemented, not just on what it promises.
4The Fix: Composition and Forwarding
With composition, our class does not extend HashSet. It holds a Set in a private field and implements the Set interface by forwarding each call to it. Following Effective Java, we split this into a reusable forwarding class and the instrumented wrapper.
Now when HashSet.addAll calls add() internally, it calls it on the HashSet object inside our wrapper, not on our wrapper. Our add() is not involved, so nothing is counted twice. Whatever the inner set does internally, today or in a future JDK, cannot affect our count.
Notice two bonuses. The wrapper works with any Set, so new InstrumentedSet<>(new TreeSet<>()) instruments a sorted set with no extra code. And it is the decorator pattern, the same idea the JDK uses in Collections.unmodifiableSet and Collections.synchronizedSet. The cost is the boilerplate of the forwarding methods, which is written once and which IDEs can generate.
5Design for Inheritance, or Forbid It
The lesson for our own classes is that a class meant to be extended must say which of its methods call which others, because subclasses depend on it. The JDK does this with the @implSpec Javadoc tag, for example to state that a method in AbstractList is implemented in terms of another. Writing such a contract is a real commitment: once documented, the self-use can never change without breaking subclasses.
So for most classes, the better default is to make them final, or to give them only private constructors with static factories, and let others reuse them through composition. In a Spring codebase, this is also why we prefer injecting a collaborator over extending a base service: the collaborator's internals can change freely, while a subclass is tied to them.
6Follow-up questions
Is inheritance ever the right choice?
Yes, when there is a genuine is-a relationship and the parent is designed for it, inside one package or library where the same people control both classes, or when the parent is an abstract class with documented extension points such as AbstractList. Extending classes across a library boundary, especially concrete classes not designed for it, is where the fragility hurts.
What is the downside of the wrapper approach?
Wrappers do not fit callback frameworks well, where an object passes a reference to itself, this, to another object for later calls. The inner object passes itself, not the wrapper, so callbacks skip the wrapper. This is sometimes called the self problem. Wrappers also break identity, since the wrapper and the inner object are different objects.
How does this relate to Spring proxies?
Spring's AOP proxies are a kind of wrapper too, and they show the same self problem: a call from inside the bean on this skips the proxy, so @Transactional on a self-invoked method does nothing. Whether we are counting adds or starting transactions, behaviour added around an object only applies to calls that go through the wrapper.
7Conclusion
In this answer, we saw that InstrumentedHashSet counts each element twice because HashSet's inherited addAll calls the overridden add() on this. The subclass depends on that undocumented self-use, which could change in any release, and new parent methods could bypass the count. Composition removes the dependency: a forwarding wrapper implements Set, delegates to a private Set and counts only in its own methods. Classes that are meant to be extended must document their self-use; the rest should be final.
Open with
The count doubles because of self-use in the parent. HashSet doesn't implement addAll itself; it inherits it from AbstractCollection, and that implementation just loops and calls add for each element.
Then, if they want more
Since our subclass overrides add, dynamic dispatch sends each of those calls to our version. So our addAll adds three, then super.addAll calls our add three times, and we get six. The deeper problem is that the subclass depends on an implementation detail of HashSet that isn't documented.
If I remove my addAll override, it happens to work today, but only because addAll calls add; a future JDK could change that and my count would silently break, and a new method in the parent that adds elements would bypass my counting entirely. That's the fragile base class problem, and it's why inheritance breaks encapsulation. The fix is composition.
I write a forwarding class that implements Set, holds a private Set, and forwards every method to it, and then an InstrumentedSet that extends the forwarding class and counts in add and addAll. Now when the inner HashSet calls add internally, it calls its own add, not mine, so three elements count as three, whatever the inner set does.
As a bonus it works with any Set, like a TreeSet. It's the decorator pattern. The general rule I follow is that a class should either be designed for inheritance, with its self-use documented, or be final, and other code reuses it through composition.
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 official documentation for the version you use. 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 "Effective Java advises favouring composition over inheritance and uses an example where...": https://scrivio-interview-library.netlify.app/java/clean-code/70cd048412/