Concepts
Concepts
OOP Concepts
Encapsulation
• Encapsulation is a practice to bind related functionality
(Methods) & Data (Variables) in a protective wrapper (Class)
with required access modifiers (public, private, default &
protected) so that the code can be saved from unauthorized
access by outer world and can be made easy to maintain.
• Encapsulation is the technique of making the fields in a class
private and providing access to the fields via public methods.
• If a field is declared private, it cannot be accessed by anyone
outside the class, thereby hiding the fields within the class.
• For this reason, encapsulation is also referred to as data
hiding.
Encapsulation
• The main benefit of encapsulation is the ability to
modify our implemented code without breaking
the code of others who use our code.
• With this feature Encapsulation gives
maintainability, flexibility and extensibility to our
code.
Example:
public class EncapTest{
private String name; • The public methods are the
private String idNum;
private int age;
access points to this class'
public int getAge(){ fields from the outside java
return age;
} world.
public String getName(){
return name;
• Normally, these methods
} are referred as getters and
public String getIdNum(){
return idNum; setters.
}
public void setAge( int newAge){
• Therefore any class that
age = newAge; wants to access the
}
public void setName(String newName){ variables should access
name = newName; them through these getters
}
public void setIdNum( String newId){ and setters.
idNum = newId;
}
}
The variables of the EncapTest class can be
access as below:
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest(); 20
t:
u ge :
encap.setName("James"); t p
Ou es A
Jam
encap.setAge(20); me
:
Na
encap.setIdNum("12343");
System.out.print("Name : " + encap.getName()+ "
Age : "+ encap.getAge());
}
}
Benefits of Encapsulation: