Java Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit.
Example: A capsule which is mixed of several medicines. 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. That’s why it is also known as data hiding.
How we can achieve encapsulation in java?
- Declare the variables of a class as private.
- Provide public setter and getter methods to modify and view the variables values.
Example Program for Encapsulation:
class EncapPro{
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;
}
}
public class RunEncapPro {
public static void main(String args[]) {
EncapPro encap = new EncapPro();
encap.setName(“Technical Speaks”);
encap.setAge(1000);
encap.setIdNum(“0123abc”);
System.out.print(“Name : ” + encap.getName() + ” Age : ” + encap.getAge());
}
}
Output: Name: Technical Speaks Age: 1000