Encapsulation in Java

Encapsulation is data hiding. When there is a private keyword for variables or attributes or methods, it cannot be accessed from outside the class. This is called encapsulation.  

In order to access those private variables or attributes from outside the class public get and set methods can be used. The following program shows encapsulation. Here x is an integer and is private. So, it cannot be accessed from outside the class. In order to access x from outside the class getNumber() and setNumber() methods are used. 

package com.company;

public class encapsulationExample {
    private int x = 4;

    public int getNumber() {
        return x;
    }

    public void setNumber(int newNumber) {
        this.x = newNumber;

    }
}

    class MainClass {
    public static void main(String[] args) {
        encapsulationExample Obj = new encapsulationExample();
        Obj.setNumber(5);
        System.out.println(Obj.getNumber());
    }
}

Output:

5
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments