Here's my code
Package a
package a;
import static net.mindview.util.Print.print;
import b.B;
public class A
{
protected void f()
{
print("This is A's protected f()");
}
public static void main(String[] args)
{
// new B().f() does not work!
// compiler will complain B.f() is not visible
A a = new B();
a.f(); // but using polymorphism here! I can invoke B.f()!
}
}
Package b
package b;
import static net.mindview.util.Print.print;
import a.A;
public class B extends A
{
protected void f()
{
print("This is B's protected f()");
}
}
The problem is a.f() in main() actually invokes the class B's protected overridden f() to which class A has no access.
Notice that A is B's superclass, and they are in different packages. A has no access to B's f().
Technically speaking, B's protected f() can only be accessed either from its subclasses or classes in the same package.
But neither condition is satisfied by class A.
So, my question here is does polymorphism actually break the rule of protected access modifier, or is there any implicit and hiding mechanism taking place during the call?
Can anybody help?
Thanks a lot.
The printing result is "This is B's protected f()".
It is a totally different question from "Understanding java's protected modifier". Please look at the code carefully!!!!
In that question, C -> A relationship. in C(subclass) create an A a = new A() (superclass), and tries to access a's protected member but fails to do so.
In my question, B -> A relationship. in "A"(superclass) create an "B" b = new B() (subclass), and tries to access b's protected member(which should not succeed) but succeeds to do so!
I think I express the difference so clearly, for any impatient programmers to quickly distinguish between two questions.