Encapsulation is a way to data hiding process where the variables of a class are hidden from other classes and can be accessed only through the defined public methods that are known as getters setters.
Example:
class Main {
public static void main(String[] args) {
Student student=new Student();
student.showData("Babul","20");
}
}
class EncapTest{
private String name;
private String age;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getAge(){
return age;
}
public void setAge(String age){
this.age=age;
}
}
class Student{
public void showData(String name, String age){
EncapTest encapTest=new EncapTest();
encapTest.setName(name);
encapTest.setAge(age);
System.out.println(encapTest.getName());
System.out.println(encapTest.getAge());
}
}
The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred to as getters and setters.
In the above code, EncapTest class is used in Student class and student properties are set to Student class. Finally, user input is taking from the main method.
Although student name and age properties are private in EncapTest class, those can be accessed throw the public getter setter from Student class.
Therefore, any class that wants to access the variables, need to access them through these getters and setters.
Leave a Reply