Talk about access modifiers in Java

  • 2020-04-01 02:19:36
  • OfStack

one

Public: all classes are accessible

Protected: all subclasses and classes under the same package can be accessed

Default: the same package class is accessible

The private: class itself is accessible

Note: when protected modifies a class property, for example


package Parent;
public class Parent{
    protected int i=5;
}
package Son;
public class Son extends Parent{
    public static void main(String[] args){
         Parent p=new Parent();
         Son s=new Son();
         System.out.println(p.i);//The first line
         System.out.println(s.i);//The second line
    }
}

Subclass access means that in the second row you have access to the property I of the parent class, not that the first row has access to the property I and the first row reports an error;

But if the Son class and Parent are in the same package, the first line is fine.


Related articles: