Java cast to superclass and call overload method

后端 未结 1 557
死守一世寂寞
死守一世寂寞 2021-01-23 18:45
abstract class A {

    int met(A a) {
        return 0;
    }

    int met(B b) {
        return 1;
    }

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

class B extends         


        
相关标签:
1条回答
  • 2021-01-23 19:13

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

    0 讨论(0)
提交回复
热议问题