I would like to understand what's happening in the example below (where a protected member is being accessed from outside the package through a subclass).
I know for classes outside the package, the subclass can see the protected member only through inheritance.
There are two packages: package1
and 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 } }
It is understood that the boo()
method in ExtendsprotectedClass
can access foo()
, since protected members can be accessed through inheritance only.
My question is, why is the foo()
method working fine when accessed through a reference in the main()
method of ExtendsprotectedClass
but will not work when accessed through the epc
reference in UsesExtendedClass
?
public static void ExtendsprotectedClass.main(String[] args){ ProtectedClass epc = new ExtendsprotectedClass(); //upcast
epc.foo(); // should be compilation error?
} – Markus Kull Aug 22 '10 at 08:52