Encapsulation
is data hiding
simply.
let's see how encapsulation happens.
Assume you create a Employee class and include two instance variables. name and salary. You don't make them private. Now what happens another class in the program can access these two variables simply by creating an object if the employee class. So what we want is to hide these both or salary information to outside classes.
If we want to hide salary We can simply declare salary as a private
variable. Now we know even another class create an object and try to access salary as before it doesn't work. Because it is a private field which is only accessible to Employee class. Now we have hidden our data.
But assume that we need a person to enter salary details of each of the employees.
I will make it more clear.
The data entering person has 3 types of data to enter woked_hours, OT and leaves
(Emplyee class has three variables for this).
We want this person to enter these details but we do not want
him to see
how the salary calculation
is done. It is done according to the mathematical equation which is inside Employee class.
So he cannot calculate and enter salary it self. But we let him see the final salary. there We create a method to get the value of the salary inside employee class. it is
public int getSalary()
{
return salary;
}
He knows this, that there are two methods he can use to access those hidden fields. set method and get method.
So he call getmethod.
yes he can see
the salary
information. Because we have created the getMethod to return salary. Now he try to use set method to enter a new salary amount to change current value of salary. so he call e.setSalary(1000);
But it gives an error. Why? because in the employee class there is no method written as
public void setSalary(int newSalary)
{
salary=newSalary;
}
We intentionally didn't write that code because we don't want him to set salary value straight away. So we have hidden some information but some we still let him access. We gave him access to Read only
. But not Write
for salary.
so wasn't it useful now that encapsulation we have done.
The same way as he is allowed to set
these fields woked_hours, OT and leaves
. for those fields we have given him access to Write only. There we intentionally do not write getter methods
. If you write both getter
and setter you are allowing him to READ/ Write
both access.
It doesn't matter only set or get, The field is private, the field is hidden already data is hidden. But some access is given through getters
and setters
.