简体   繁体   English

Java转换为超类并调用重载方法

[英]Java cast to superclass and call overload method

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());
    }
}

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? 程序将返回3,而我期望的是0。为什么方法f中的第一个强制转换什么都不做,而第二个有效? Is it because in the A and B classes the met methods are overloaded and therefore static binding is used? 是因为在A和B类中,met方法被重载,因此使用了静态绑定吗?

That's just the way polymorphism works. 这就是多态性的工作方式。 Just consider this example: 请考虑以下示例:

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

This would as expected call the correct method B#met(...) . 如预期的那样,将调用正确的方法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. 对象的方法表不只是因为您更改了存储Object的变量的类型而改变,因为Object与其方法之间的绑定比存储类型与与之相关的方法之间的绑定更强大。它。 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). 第二种类型起作用,因为输入的类型被强制转换为A ,因此该方法将其识别为A (输入存储的类型具有比Object类型更强的绑定)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM