权限修饰符

public  protected   默认(什么都不写)  private

1、本类中都可访问

class Father{
    private void show1(){
        System.out.println("show1 private");
    }
    void show2(){
        System.out.println("show2 默认");
    }
    protected void show3(){
        System.out.println("show3 protected");
    }
    public void show4(){
        System.out.println("show4 public");
    }

    public static void main(String[] args) {//本类中每个修饰符都可以访问
        Father father=new Father();
        father.show1();
        father.show2();
        father.show3();
        father.show4();
    }
}
class Son extends Father{
        }

2、本包中,除private外都可访问

public class XiuShiFuDemo {//同包下的类可以反问带有public protected和默认修饰符的方法
    public static void main(String[] args) {
        Father father=new Father();
        father.show4();
        father.show3();
        father.show2();
        Son son=new Son();
        son.show2();
        son.show3();
        son.show4();
    }
}

3、不同包下的子类

可以访问protected和public

class Son extends Father {
    public static void main(String[] args) {
        Father father=new Father();
        father.show4();
        
        Son son=new Son();
        son.show4();
        son.show3();
    }
}

4、不同包下的无关类

可以访问public修饰的

public class TestXiuShiFuDemo {
    public static void main(String[] args) {
        Father father=new Father();
        father.show4();
    }
}
原文地址:https://www.cnblogs.com/wyj96/p/11750986.html