说到protected访问符,我首先想到的是包内和子类(或者子类的子类)可以访问。
但是其中却有值得我注意的:
我先在test01包中定义Father类:
package test01;
public class Father {
protected void s() {
System.out.println("可以调用");
}
}
然后在test02包中定义SonA类并且继承Father
package test02;
import test01.Father;
public class SonA extends Father{
public static void main(String[] args) {
// Father father = new Father();
// father.s(); //这里会报错The method s() from the type Father is not visible
SonA sA = new SonA();
sA.s();//子类继承了父类,当然可以访问继承过来的protected方法,不报错
}
}
在test02包中定义SonB类并且继承Father
package test02;
import test01.Father;
public class SonB extends Father{
public static void main(String[] args) {
SonA sA = new SonA();
sA.s(); // 这里会报错,The method s() from the type Father is not visible
}
}
总结:总之就是只能自己用自己继承过来的protected方法,不能在自己方法中调用兄弟子类继承的protected也不能调用父类的protected方法。