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
Code example
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);
    }
}