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.


class Main {
    public static void main(String[] args) {
        Student student=new Student();


class EncapTest{
    private String name;
    private String age;
    public String getName(){
        return name;
    public void setName(String name){
    public String getAge(){
        return age;
    public void setAge(String age){


class Student{
    public void showData(String name, String age){
        EncapTest encapTest=new EncapTest();

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.

about author



If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *