What is encapsulation?
Encapsulation means wrapping up things in a single unit, it’s like a process through which capsules are created. In creating we mix up different medicines and wrap them in a single capsule. In OOPs data and functions, which operates on the data, are wrapped in a single unit called class. This is what encapsulation is.
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
Below is an example of encapsulation:
class Employee{
private String empId;
private String empName;
public void showDetails(){
System.out.println("Emp Id : "+this.empId+" Emp Name : "+this.empName);
}
public void setEmpId(String empId){
this.empId = empId;
}
public void setEmpName(String empName){
this.empName = empName;
}
}
We can see in above programs variables empId and empName are declared as private so we cannot access them directly. In order to access those variables we need to create an instance of Employee class and then we can access public set method for changing their values. Let’s see how we can do that :
class MainClass{
public static void main(String []args){
Employee obj = new Employee();
obj.setEmpId("EMP10001");
obj.setEmpName("Nishesh Pratap Singh");
obj.showDetails();
System.out.println("Changing Emp Name");
obj.setEmpName("Rahul Singhania");
obj.showDetails();
}
}
When we execute above program we will get following output on console :
Emp Id : EMP10001 Emp Name : Nishesh Pratap Singh
Changing Emp Name
Emp Id : EMP10001 Emp Name : Rahul Singhania
Benefits of Encapsulation are as follows :
1. Through encapsulation we can made fields of a class read-only or write-only.
2. A class can have total control over what can be stored in it's field and what cannot.
No comments:
Post a Comment