Encapsulation in Java
Encapsulation simply means binding object state(fields) and behavior (methods) together. If you are creating class, you are doing encapsulation.
The goal of encapsulation is to keep implementation details hidden from users. When a data member is private, it can only be accessed by other members of the same class. No outside class allows access to a class's private data member (variable).
Encapsulation in Java |
However, if we provide public getter and setter methods to update (for example, void setEmpID(int empid) and read (for example, int getEmpID()) the private data fields, the outside class can use those public methods to access those private data fields.
Private fields and their implementation are hidden from outside classes since data can only be accessed by public methods. Encapsulation is also known as data hiding.
Example :
Encapsulation in Java is implemented as follows:
1) Make instance variables private, so they can't be accessible from outside the class. These variables can only be set and get via the class's methods.
2) In the class, have getter and setter methods to set and get the values of the fields.
class EncapsulationTest
{
private int empid;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpID()
{
return empid;
}
public String getEmpName()
{
return empName;
}
public int getEmpAge()
{
return empAge;
}
public void setEmpAge(int inputValue)
{
empAge = inputValue;
}
public void setEmpName(String inputValue)
{
empName = inputValue;
}
public void setEmpID(int inputValue)
{
empid = inputValue;
}
}
public class EncapsTest
{
public static void main(String args[])
{
EncapsulationTest obj = new EncapsulationTest();
obj.setEmpName("John");
obj.setEmpAge(26);
obj.setEmpID(0445);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee ID: " + obj.getEmpID());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output :
Employee Name : John
Employee ID : 0445
Employee Age : 26
All three data members (or data fields) in the above example are private (see: Access Modifiers in Java) and cannot be accessed directly. Only public methods have access to these fields. Using the OOPs encapsulation concept, the fields empName, empid, and empAge are hidden data fields.
Advantages of Encapsulation :
You may make a class read-only or write-only by giving just a setter or getter method. In other words, the getter and setter methods are optional.
It gives you complete control over your data. You may put the logic within the setter method if you want to set the value of id to be larger than 100 only. You may implement logic in the setter methods to prevent negative integers from being stored.
Because other classes will not be able to access the data through the private data members, it is a technique to achieve data hiding in Java.