Encapsulation
By Sanghamitra Panda
Java Encapsulation
• Encapsulation in Java is a mechanism of wrapping the data (variables)
and code acting on the data (methods) together as a single unit. 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.
• The following are important points about encapsulation.
• Better Code Management: We can change data representation and
implementation any time without changing the other codes using it if we
keep method parameters and return values the same. With encapsulation,
we ensure that no other code would have access to implementation details
and data members.
• Simpler Parameter Passing: When we pass an object to a method,
everything (associated data members and methods are passed along). We
do not have to pass individual members.
• getter and setter: getter (display the data) and setter method ( modify the
data) are used to provide the functionality to access and modify the data,
and the implementation of this method is hidden from the user. The user
can use this method, but cannot access the data directly.
Java Encapsulation Example
/* File name : EncapTest.java */ return idNum;
public class EncapTest { }
private String name;
private String idNum; public void setAge( int newAge) {
private int age; age = newAge;
}
public int getAge() {
return age; public void setName(String newName) {
} name = newName;
}
public String getName() {
return name; public void setIdNum( String newId) {
} idNum = newId;
}
public String getIdNum() { }
• The public setXXX() and getXXX() methods are the access points of
the instance variables of the EncapTest class.
• Normally, these methods are referred as getters and setters.
Therefore, any class that wants to access the variables should access
them through these getters and setters.
/* File name : RunEncap.java */
public class RunEncap { public String getName() {
return name;
public static void main(String args[]) { }
EncapTest encap = new EncapTest();
encap.setName("James"); public String getIdNum() {
encap.setAge(20); return idNum;
encap.setIdNum("12343ms"); }
System.out.print("Name : " + encap.getName() + " Age : " + public void setAge( int newAge) {
encap.getAge()); age = newAge;
} }
}
public void setName(String newName) {
public class EncapTest { name = newName;
private String name; }
private String idNum;
private int age; public void setIdNum( String newId) {
idNum = newId;
public int getAge() { }
return age; }
}