让我们以下面的代码:继承的内部类的私有方法
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();
}
}
我预计写代码B
。代替写入A
。
它可能会感到奇怪(至少对我来说)一个类可以调用它包含的内部类的私有方法(为什么他们这样做?),但我真正无法理解的是为什么多态不起作用。
我的意思是,如果从Test.main()
我们可以打电话A.testMethod()
很明显,我们也打电话B.testMethod()
。 Java也可以确定一个对象的动态类型,为什么Java调用声明类型的方法而不是动态类型?这种行为可以被检查:
public static void main(String[] args) {
B b = new Test().new B();
A a = b;
b.testMethod(); // writes B
a.testMethod(); // writes A
}
另外,为什么会发生这种情况,只有当Test.A.testMethod()
是private
?