Monday, June 17, 2013

Abstraction and Encapsulation

Definition

Encapsulation is the process of hiding irrelevant data from the user. Or in other word encapsulation is a process of hiding all the internal details of an object from the outside world.

Abstraction is just opposite of encapsulation. Abstraction is mechanism to show only relevant data to user. Hence it is a process of representation of only essential features of an object.



Learning

“Difference  between Abstraction vs Encapsulation” is a wrong question. Oops is not playing an IPL T20 match. It should be “What is Abstraction and Encapsulation ?” Simply Encapsulation is a process of hiding data into  object. In other words wrap data and information related to the class in one concrete box to prevent access from outside  world. It is somewhat like a capsule and that is why it is called encapsulation.

Abstraction is the process of encapsulation. Confused ? Ok, let me explain in simple word. Definition says “Abstraction is to show only relevant data to the user.” Means it is the process to show relevant data or alternatively hide the unwanted data. As the dictionary meaning of the word “abstraction”, abstraction abstract meaningful data and expose the same to user.

“A good encapsulation need good levels of abstraction.”

Oh.. I missed one thing. You geeks always confused with Abstraction and the keyword abstract. Both are different thing. Abstract, private, protected, internal, protected internal and public are the keywords and access modifier just to implement abstraction and encapsulation.
 

Example 

In the below class there are 5 members. Two are public and three are private. EmpID and EmpName are declared as public. These two member is exposed to outside of the Employee class. Hence it is called abstraction. On the other hand Salary,Bonus,Gratuity are declared as private , means it can only be accessable within the Employee class, or we can say these three are capsuled under Employee class. So it is called encapsulation.