In the example in the article you linked to:
set.addAll(Arrays.asList("Snap", "Crackle", "Pop"));
This calls InstrumentedHashSet.addAll
.
InstrumentedHashSet.addAlladds 3 to the counter, then calls
HashSet.addAll`.
HashSet.addAll
calls this.add
three times to add each of the elements.
But this.add
is really a call to InstrumentedHashSet.add
!
Each call to InstrumentedHashSet.add
adds 1 to the counter and calls super.add
.
Each HashSet.add
call does the actual work of adding the element to the set.
The end result is that we have added 6 to the counter, not 3 as you would expect.
In order for InstrumentedHashSet
to be implemented correctly, it needs to know how HashSet.addAll
is implemented, and NOT increment the counter in addAll
. But that knowledge breaks encapsulation. A subclass should not need to know how its superclass is implemented.
Can anyone please explain how composition is avoiding this problem
It avoids it because when HashSet.addAll
calls this.add
, those calls to this.add
are not calls to InstrumentedHashSet.add
. They are direct calls to HashSet.add
.
In fact, provided that HashSet.addAll
implements the Set.addAll
contract, it doesn't matter to InstrumentedHashSet
how it its implemented. No breaking of encapsulation here.
HashSet
calls its ownadd
and not the wrapper'sadd
.