Monday, February 4, 2008

Inheritance Breaks Encapsulation

"Inheritance Vs Encapsulation" ??

What is Encapsulation ?
Dictionary meaning : HIDING THE INFORMATION  { with reference to OOP }

There is always a debate that Hiding the information and Encapsulation are different concept. In my opinion - 'Hiding the information' is a principle and Encapsulation is a technique.!
Anyway the more important question is - Why do need Encapsulation ?

Analogy:
Suppose we have a DVD Player. The main function of DVD player is to read the DVD Disc. For a DVD Player, it doesn't matter how the information was burn onto DVD.
Either you use Technique A or B, DVD Player doesn't care.

This is "Encapsulation". By the way - DVD is hiding how information is stored on it.
In TECHNICAL Terms - If a class implements PERFECT Encapsulation, and It we make changes to that class; we don't need to make changes in the dependent classes.


HOW INHERITANCE BREAKS IT?
As per concept of INHERITANCE, when class A inherits class B, A get to konw implementation details of all public, protected, and default methods of B (depending upon access level). Though it doesnt mean that A use all those details. The point is A knows all the details of B. So we can say that - INFORMATION IS NOT HIDE ANY MORE.

If we fuse this concept this to our DVD example -
We have a DVD player which can only play DVD which were burnt using X technology. If one changes technology from X to Y, one has to change DVD player.

This elaborate - why it is often said "Inheritance Breaks Encapsulation"