Encapsulation in Java

Encapsulation means hiding the implementation details from the outside world.

Below image shows how encapsulation is achieved in Java by declaring the private members of the class. Remember that We can not access the private members from outside of the class. Thus, any changes made inside the class with respect to private members do not impact outside classes.

 

Encapsulation in Java

Encapsulation in Java

Below example illustrates how encapsulation works in Java.

package encapsulation;

/**
 * Created by ssalunke on 19/04/2016.
 */
public class Encapsulation {
    public static void main(String [] args){

        A a1 = new A();

        //We can not access private members from here
        //Below line will throw compilation error saying a has private access
        //a1.a
        //Below line will throw compilation error saying seta has private access
        //a1.seta(1)

        //We can access public members from outside of class
        a1.display();
    }
}


class A{
    private int a;
    private String s;

    private void seta(int a){
        this.a = a;
    }

    public void display(){
        System.out.println("Display");
    }

}

Here is the output of above code.
Display

You may also like...