Ambiguous java hierarchy(模糊的java层次结构)
问题描述
我的问题是为什么下面的 x.proc(z) 打印 57 而不是打印 39 ?
My question is why x.proc(z) below does print 57 instead of printing 39 ?
class X
{
protected int v=0;
public X() {v+=10; System.out.println("constr X");}
public void proc(X p) {System.out.println(43);}
}
class Y extends X
{
public Y() {v+=5;System.out.println("constr Y");}
public void proc(X p) {System.out.println(57);}
public int getV() {return v;}
}
class Z extends Y
{
public Z() {v+=9;System.out.println("constr Z");}
public void proc(Z p) {System.out.println(39);}
}
class Main
{
public static void main(String argv[])
{
X x = new Z(); // v=24
Y y = new Z(); // v=24
Z z = new Z(); // v=24
x.proc(z); //57
}
}
X x 指的是一个 Z 对象,而类 Z 确实有方法 proc(Z p) 但它也有方法proc(X p).此外,参数 z 的类型为 Z,因此打印 39 是合理的.
X x refers to a Z object, and class Z does have the method proc(Z p) but it also has the method proc(X p). Also the parameter z is of type Z so it would be reasonable to print 39.
推荐答案
方法
public void proc(Z p) {System.out.println(39);}
在 Z 中不覆盖
public void proc(X p) {System.out.println(43);}
在 X 中,因为它将域限制为 Z 而不是 X.
in X because it restricts the domain to Z instead of X.
然而,Y中的类似方法确实覆盖了X中的proc.
However, the analogous method in Y does override proc in X.
由于x的编译时类型是X,唯一的方法签名是匹配 x.proc(z) 是 public void proc(X p) 的.直到现在才进行动态调度,并且选择并执行来自 Y 的覆盖版本,结果如预期的那样输出57".
Since the compile time type of x is X, the only method signature that
matches x.proc(z) is that of public void proc(X p). Only now does the dynamic dispatch take place, and the overriding version from Y is selected and executed, which results in output "57", as expected.
这篇关于模糊的java层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模糊的java层次结构
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
