我想了解下面的例子中发生了什么(在一个受保护的成员从包外面通过一个子类访问).
我知道包外的类,子类只能通过继承来看到受保护的成员.
有两个软件包: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
}
}
可以理解,ExtendsprotectedClass中的boo()方法可以访问foo(),因为受保护的成员只能通过继承访问.
我的问题是,为什么在通过ExtendprotectedClass的main()方法中引用访问时,foo()方法工作正常,但是通过UsesExtendedClass中的epc引用进行访问时,它将无法正常工作?