模棱两可的Java层次结构 [英] Ambiguous java hierarchy

查看:70
本文介绍了模棱两可的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);}

中的

不会覆盖

in Z does not override

public void proc(X p) {System.out.println(43);}

中的

,因为它将域限制为Z而不是X.

但是,Y 中的类似方法确实会覆盖X中的proc.

由于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层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆