为什么用//1标记的行显示57而不是39? [英] Why does the line marked with //1 print 57 instead of 39?

查看:372
本文介绍了为什么用//1标记的行显示57而不是39?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class X {
    protected int v = 0;

    public X() {
        v += 10;
    }

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

class Y extends X {
    public Y() {
        v += 5;
    }

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

    public int getV() {
        return v;
    }
}

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        System.out.println(39);
    }
}

class Main {
    public static void main(String[] args) {
        X x = new Z();
        Y y = new Z();
        Z z = new Z();
        x.proc(z);// 1
        System.out.println(y.getV());
    }
}

据我了解,在类型为X的对象上调用proc()方法,该对象持有"类型Z,并且在运行时JVM检查对象的类型,并使用Y的proc()方法覆盖该方法.但是方法参数的类型为Z,为什么它不从Z类调用重载方法?

From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?

推荐答案

发生这种情况是因为您没有在Z类中覆盖方法'proc'.覆盖该方法时,不能使用参数,该参数具有原始参数类的子类.如果在Z.proc(Z p)上添加@Override,则不会编译您的代码.

It happens because you don't override the method 'proc' in Z class. When you overriding the method, you can't use argument, which has a child class of original argument class. If you add @Override on Z.proc(Z p), your code will be not compiled.

让我们想象一下这是可能的,那么您可以在执行Z.proc(Z p)的过程中使用Z类中的某些方法.

Let's imagine that it is possible, then you can use some method from Z class during executing Z.proc(Z p).

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        someActions();
        System.out.println(39);
    }

    private void someActions() {
        System.out.println("Some actions");
    }

}

现在执行

X x = new Z();
x.proc(new X());

应该怎么办? X类中没有"someActions"方法.应该如何运作?这就是Z.proc(Z p)不覆盖X.proc(X p)的原因. Z类具有两种不同的方法:Z.proc(Z p)和Y.proc(X p).

What should happens? There is no 'someActions' method in the X class. How it should works? That's why Z.proc(Z p) doesn't override X.proc(X p). Class Z, has two different methods: Z.proc(Z p) and Y.proc(X p).

致电时

X x = new Z();
x.proc(new Z());

JVM寻找具有最接近Z类的签名"proc(X)"的替代方法或原始方法(因为X类具有"proc(X)"方法)在Y类中找到它并执行Y.proc(x p).这就是为什么您在输出中看到"57"的原因.

JVM looks for closest overrided or original method with signature 'proc(X)' to Z class (because X class has 'proc(X)' method) finds it in Y class and executing Y.proc(x p). That's why you see '57' in output.

这篇关于为什么用//1标记的行显示57而不是39?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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