java中的public,protected,private权限修饰

public和private基本没问题,主要是默认的和protected之间的区别

同一包中默认的和protected一样,所以来看看不同包的情况

看下如下代码,两个类位于不同包:

public class Base {
    int i = 0;
}
public class Extends extends Base {
    public void test(){
        Extends e = new Extends();
        Base b = new Base();
        //e.i = 1;//编译无法通过
        //b.i = 1;//编译无法通过

    }
}

加上protected修饰符:

public class Base {
    protected int i = 0;
    
}
public class Extends extends Base {
    public void test(){
        Extends e = new Extends();
        Base b = new Base();
        e.i = 1;
        //b.i = 1;//编译无法通过

    }
}
原文地址:https://www.cnblogs.com/vinozly/p/5154190.html