Encapsulation-
The binding of data into single entity called as “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
Employee e2= new Employee();
e2.salary=-3000; //case 2
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;
public void setSalary(int sal) {
if (sal > 0) {
salary = sal;
} else {
salary = 0;
}
}
public int getSalary() {
return 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.
Program for Encapsulation-
public class EncapsulationTest {
public static void main(String[] args) {
Employee employee= new Employee ();
employee.setSalary(-5000);
System.out.println("salary>>"+employee.getSalary());
}
}
Confidential
Program for Encapsulation
public class Student {
private String name; // global Variable
public String getName() {
return name;
}
public void setName(String studentName) {
name = studentName;
}
public class mainClass {
public static void main(String[] args) {
Student student = new Student(); //Object
Creation
student.setName("Ajay"); // Method calling
String studentName = student.getName();
System.out.println("Student Name
is :"+studentName);
System.out.println("Student Name is :
"+student.getName());
}
Confidential