protected修饰的成员变量和方法可以被包外的子类访问到。
这里被包外子类访问实质并不是在子类中通过创建父类对象来访问这个protected方法, 而是可以通过创建子类对象来访问。
通过继承,子类就可以获得了父类方法的地址信息,并把这些信息保存到自己的方法区,这样就可以通过子类对象访问自己的方法区从而间接的访问父类的方法(重写的话,就直接访问子类自己重写后的方法)。
子类只是通过继承产生了自己能访问的方法表,包括父类的保护区域(实例方法),并无权限访问父类对象的方法表中保护区域
见下面的例子:
package com.package01;
public class Father {
protected void method1() {
}
protected static void method2() {
}
}
package com.package02;
import com.package01.Father;
public class Child extends Father {
public void test() {
this.method1();
super.method1();
Child child1 = new Child();
child1.method1();
Father father1 = new Father();
father1.method1(); // 编译报错
this.method2();
super.method2();
Child child2 = new Child();
child2.method2();
Child.method2();
Father father2 = new Father();
father2.method2();
Father.method2();
}
}
解释:
1. 类B继承了类A,包括保护型方法区域,所以能通过B对象来调用这个区域访问该方法。
2. 类B只是继承了类A的保护型方法区域,类B并没有继承对象A的保护型方法区域,因此类B无法查看对象A的保护型方法区域。
参考博客:https://blog.csdn.net/dawn_after_dark/article/details/74453915