我想了解以下示例中的情况(通过包从子类外部访问受保护的成员)。
我知道对于包外部的类,子类只能通过继承才能看到受保护的成员。
有两个包:package1和package2。
package1: ProtectedClass.java
package org.test.package1;
public class ProtectedClass {
protected void foo () {
System.out.println("foo");
}
}
package2: ExtendsprotectedClass.java
package org.test.package2;
import org.test.package1.ProtectedClass;
public class ExtendsprotectedClass extends ProtectedClass {
public void boo() {
foo(); // This works,
// since protected method is visible through inheritance
}
public static void main(String[] args) {
ExtendsprotectedClass epc = new ExtendsprotectedClass();
epc.foo(); // Why is this working?
// Since it is accessed through a reference,
// foo() should not be visible, right?
}
}
package2: UsesExtendedClass.java
package org.test.package2;
public class UsesExtendedClass {
public static void main(String[] args) {
ExtendsprotectedClass epc = new ExtendsprotectedClass();
epc.foo(); // CompilationError:
// The method foo() from the type ProtectedClass
// is not visible
}
}
可以理解,中的boo()方法ExtendsprotectedClass可以访问foo(),因为受保护的成员只能通过继承来访问。
我的问题是,为什么是foo()方法,通过在基准访问时,工作正常main()的方法ExtendsprotectedClass ,但
将无法正常工作 通过访问时epc的参考UsesExtendedClass?