Let's take the following code:
public class Test {
class A {
public A() {}
private void testMethod() {
System.out.println("A");
}
}
class B extends A {
public B() { super(); }
private void testMethod() {
System.out.println("B");
}
}
public Test() { }
public A get() {
return new B();
}
public static void main(String[] args) {
new Test().get().testMethod();
}
}
I would expect that code to write B
. A
is written instead.
It may feel weird (at least to me) the fact that a class can call private methods of the inner classes that it contains (why did they make it that way?), but what i really can't understand is why polymorphism doesn't work.
I mean, if from Test.main()
we can call A.testMethod()
it's obvious we call also call B.testMethod()
. Java can also determine the dynamic type of an object so, why does Java call the method of the declared type instead the one of the dynamic type? This behavior can be checked:
public static void main(String[] args) {
B b = new Test().new B();
A a = b;
b.testMethod(); // writes B
a.testMethod(); // writes A
}
Also, why does this happen only when Test.A.testMethod()
is private
?