Lec14_Encapsulation
Lec14_Encapsulation
Advantage of encapsulation :
It provides you the control over the data. Suppose you want to set the value of id which should
be greater than 100 only
It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and
fast to create an encapsulated class in Java.
Example-
Class is the entity which contains variables and methods.
Class Employee{
int salary;
public int getEmployee(){
return 1;
}
}
Why ?
Employee e1= new Employee();
e1.salary=5000; //case 1
Confidential
In this example, case 1, we are passing the 5000 salary to the employee that is correct but case 2,
we are passing the salary -3000 that is the negative salary.
So salary can not be negative.
How we are going to achieve this by using encapsulation-
class Employee {
private int salary;
In this example, we are checking the whether the salary is greater than zero. Because salary
cannot be negative so in this way, we are going to achieve the encapsulation.
Note- Always keeps global variables private and allows others to assign values through public
methods.
Confidential
Program for Encapsulation
Confidential