google.com, pub-8786015629279405, DIRECT, f08c47fec0942fa0 Write a Program to Implement Encapsulation in Java

Write a Program to Implement Encapsulation in Java

0
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


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Thank you for your interest 😊

We will back shortly after reviewing...

Thank you for your interest 😊

We will back shortly after reviewing...

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top