user1720616 user1720616 - 2 months ago 9
Java Question

Encapsulation vs Information hiding

What exactly are the differences between Ecapsulation and Information Hiding?

Well i know that making fields private and then making setter and getter of the fields is ecapsulation.However does encapsulation mean just this?

suppose i have a class as described below.

public Class IsThisEncapsulation
{
public int age;

public void setAge(int age)
{
this.age=age;
}

public int getAge()
{
return age;
}
}


Now is the class IsThisEncapsulation an example of Encapsulation?

Now would making the field 'age' in the above class private achieve informaton hiding?

Could you please give me clear examples that will help me distinguish these concepts clearly?

Answer

Well i know that making fields private and then making setter and getter of the fields is ecapsulation. However does encapsulation mean just this?

---> Encapsulation is an OOP concept where object state(class fields) and it's behavior(methods) is wrapped together. Java provides encapsulation using class.

Information Hiding :

--> mechanism for restricting access to some of the object's components. Your above example is the example of Information Hiding if you make age private.


Initially Information/Data Hiding was considered the part of Encapsulation, and the definitions of Encapsulation would be as :

  • A language mechanism for restricting access to some of the object's components.
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition.

Reference: wikipage