Hi, I was curious to understand what's happening here.( a protected member being accessed outside the package through a subclass ) I know for classes outside the package, the subclass can see the protected member only through inheritance.
consider two packages - package1 and package2.
1) package1 - ProtectedClass.java
package org.test.package1;
public class ProtectedClass {
protected void foo () {
System.out.println("foo");
}
}
2) package2 - ExtendsprotectedClass.java
package org.test.package2;
import org.test.package1.ProtectedClass;
public class ExtendsprotectedClass extends ProtectedClass{
public void boo() {
foo(); // Correct.. since protected method is visible through inheritance
}
public static void main(String[] args){
ExtendsprotectedClass epc = new ExtendsprotectedClass();
epc.foo(); // Why is this working since its accessed through a reference. foo() should not be visible right ?
}
}
3) package2 - UsesExtendedClass.java
package org.test.package2;
public class UsesExtendedClass {
public static void main(String[] args) {
ExtendsprotectedClass epc = new ExtendsprotectedClass();
epc.foo(); // Compilation Error- The method foo() from the type ProtectedClass is not visible
}
}
Its Understood that boo() method in ExtendsprotectedClass
can access foo(), since protected member can be accessed through inheritance only.
My Query is, why is the foo() method working fine when accessed through a reference in main() method of ExtendsprotectedClass
and will not work
when accessed through reference in UsesExtendedClass
.