Java cast to superclass and call overload method

2019-02-28 18:46发布

问题:

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? Is it because in the A and B classes the met methods are overloaded and therefore static binding is used?

回答1:

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(...). 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).