Encapsulation Example Java Program


Definition

If a class disallows calling code from accessing internal object data and forces access through methods only, this is a strong form of abstraction or information hiding known as encapsulation. This is useful because it prevents the external code from being concerned with the internal workings of an object. This facilitates code refactoring, for example allowing the author of the class to change how objects of that class represent their data internally without changing any external code.

Encapsulation Example Program

class Main{
    private int serialnum;
    private String name;
    private int age;
    public int getEmpserialnum(){
        return serialnum;
    }
    public String getEmpName(){
        return name;
    }
    public int getEmpAge(){
        return age;
    }
    public void setEmpAge(int newValue){
        age = newValue;
    }
    public void setEmpName(String newValue){
        name = newValue;
    }
    public void setEmpSSN(int newValue){
        serialnum = newValue;
    }
}
public class EncapsulationDemo{
    public static void main(String args[]){
        Main obj = new Main();
        obj.setEmpName("XYZ");
        obj.setEmpAge(32);
        obj.setEmpSSN(3121222);
        System.out.println("Employee Name: " + obj.getEmpName());
        System.out.println("Employee Serial number: " + obj.getEmpserialnum());
        System.out.println("Employee Age: " + obj.getEmpAge());
    } 
}

Sample Output

Output is:
Employee Name: XYZ
Employee Serial number: 3121222
Employee Age: 32