我想了解下面的示例中发生了什么(通过子类从包外部访问受保护的成员)。
我知道对于包外的类,子类只能通过继承看到受保护的成员。
有两个包:package1和package2。
package1:ProtectedClass.javapackage org.test.package1; public class ProtectedClass { protected void foo () { System.out.println("foo"); } }package2:ExtendsprotectedClass.javapackage 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.javapackage 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 } }
可以理解的是can access中的boo()方法,因为受保护的成员只能通过继承来访问。ExtendsprotectedClassfoo()
我的问题是,为什么通过方法中foo()的引用访问该方法工作正常main(),ExtendsprotectedClass 但通过引用访问时无法正常工作?epcUsesExtendedClass
