JAVA - ENCAPSULATION
http://www.tutorialspoint.com/java/java_encapsulation.htm Copyright © tutorials point.com
Encapsulat ion is one of t he four fundament al OOP concept s. The ot her t hree are inherit ance,
polymorphism, and abst ract ion.
Encapsulat ion is t he t echnique of making t he fields in a class privat e and providing access t o t he
fields via public met hods. If a field is declared privat e, it cannot be accessed by anyone out side t he
class, t hereby hiding t he fields wit hin t he class. For t his reason, encapsulat ion is also referred t o as
dat a hiding.
Encapsulat ion can be described as a prot ect ive barrier t hat prevent s t he code and dat a being
randomly accessed by ot her code defined out side t he class. Access t o t he dat a and code is t ight ly
cont rolled by an int erface.
The main benefit of encapsulat ion is t he abilit y t o modify our implement ed code wit hout breaking
t he code of ot hers who use our code. Wit h t his feat ure Encapsulat ion gives maint ainabilit y, flexibilit y
and ext ensibilit y t o our code.
Example:
Let us look at an example t hat depict s encapsulat ion:
/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
The public met hods are t he access point s t o t his class' fields from t he out side java world. Normally,
t hese met hods are referred as get t ers and set t ers. Therefore any class t hat want s t o access t he
variables should access t hem t hrough t hese get t ers and set t ers.
The variables of t he EncapTest class can be access as below::
/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}
This would produce t he following result :
Name : James Age : 20
Benefit s of Encapsulat ion:
The fields of a class can be made read-only or writ e-only.
A class can have t ot al cont rol over what is st ored in it s fields.
The users of a class do not know how t he class st ores it s dat a. A class can change t he dat a
t ype of a field and users of t he class do not need t o change any of t heir code.