Search code examples
javainheritanceencapsulation

Inhertitance breaks encapsulation


I have seen many articles where it says inheritance breaks encapsulation

http://igstan.ro/posts/2011-09-09-how-inheritance-violates-encapsulation.html

But I am unable to understand the concept behind it. in the given example

Can anyone please explain how composition is avoiding this problem


Solution

  • 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 callsHashSet.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.