I am confused with method dispatching in java. Why does the first method "a.m1(b)" call to the class A?

The calling variable is a. And its runtime type is B, isn't it?

class A {
    public void m1(A a){
        System.out.println("A-m1");
    }
    public void m1(){
        System.out.println("A-m1");
    }

}
class B extends A {
    public void m1( B b){
        System.out.println("B-m1");

    }
    public void m1(){
        System.out.println("B-m1");

    }

}
public class HelloWorld {
    public static void main(String[] args) {

    B b = new B();  
    A a = new B();

        a.m1(b);//prints A-m1
        a.m1();//prints B-m1

    }

}
有帮助吗?

解决方案

Overload resolution is done based on compile-time types. A variable of type A only exposes the methods m1() and m1(A). Because you pass in a parameter, m1(A) is invoked; or rather, the appropriate override thereof. Except that m1(B) is not an override of m1(A). (Off the top of my head, I don't know if overrides can widen argument signatures, but they certainly can't narrow them.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top