Encapsulation

By default class members have package scope. So they are accessible from anywhere in this package.

There are three modifiers that change access rules for class members.

  • public - member accessible from anywhere
  • protected - member accessible from same package and from its child classes
  • private - member accessible only for owner class
public class  Parent{
    public int field1 = 10;
    protected int field2 = 11;
    private int field3 = 12;
    
     public void method1(){
        System.out.println(field1);
        System.out.println(field2);
        System.out.println(field3);
    }
}
public class Child extends Parent { public void method1(){ System.out.println(field1); System.out.println(field2); // error, field3 is private member in parent class System.out.println(field3); } public void method2(){ Parent parent = new Parent(); System.out.println(parent.field1); System.out.println(parent.field2); // error, field3 is private member in parent class System.out.println(parent.field3); } public class Other{ public void method1(){ Parent parent = new Parent(); System.out.println(parent.field1); // error if Parent and Other in different packages System.out.println(parent.field2); // error, field3 is private member in parent class System.out.println(parent.field3); } }