Java转换为超类并调用重载方法 [英] Java cast to superclass and call overload method

查看:152
本文介绍了Java转换为超类并调用重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

abstract class A {

    int met(A a) {
        return 0;
    }

    int met(B b) {
        return 1;
    }

    int met(C c) {
        return 2;
    }
}

class B extends A {

    int met(A a) {
        return 3;
    }

    int met(B b) {
        return 4;
    }

    int met(C c) {
        return 5;
    }
}

class C extends B {
    int f() {
        return ((A)this).met((A)this);
    }
}

public class teste {
    public static void main(String args[]) {
        C x = new C();
        System.out.println(x.f());
    }
}

程序将返回3,我期待0。为什么方法f中的第一次投射什么都不做而第二次投射有效?是因为在A和B类中,met方法是重载的,因此使用静态绑定?

The program will return 3 and I was expecting 0. Why does the first cast in the method f do nothing and the second one works? Is it because in the A and B classes the met methods are overloaded and therefore static binding is used?

推荐答案

这就是方式多态性有效。请考虑这个例子:

That's just the way polymorphism works. Just consider this example:

A a = new C();
a.met(a);

这将按预期调用正确的方法 B#met(... )。对象的方法表不仅会更改,因为您更改了存储 Object 的变量的类型,因为之间的绑定对象,它的方法比存储类型和与之相关的方法之间的方法更强。第二种类型有效,因为输入的类型被转换为 A ,因此该方法将其识别为 A (输入存储的类型具有比 Object 类型更强的绑定。

This would as expected call the correct method B#met(...). The method-tables for an object don't just change because you change the type of the variable you stored the Object in, since the binding between an Object and it's methods is stronger than the one between the storage-type and the methods related to it. The second type works, because the type of the input is casted to A and thus the method recognizes it as A (the type of the input-storage has stronger binding than the Object type).

这篇关于Java转换为超类并调用重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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