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 的变量的类型而改变,因为 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).

相关文章