java method overload inheritance and polymorphism

假如想象 提交于 2019-12-20 04:25:09

问题


Here's a test practice question i came across, would appreciate your help in making me understand the concepts

Let Hawk be a subclass of Bird. Suppose some class has two overloaded methods void foo(Hawk h) and void foo(Bird b). Which version would get executed in the call foo(x) after the declaration Bird x = new Hawk();

Here's the code i have so far, could someone explain to me why foo(bird b) gets executed?

public class MPractice {
    public static void main(String args[]) {
        Bird x = new Hawk();
        Third y = new Third();
        y.foo(x);
    }

}



 public class Third {
    void foo(Hawk h) {
        System.out.println("Hawk");
    }
    void foo(Bird b) {
        System.out.println("Bird");
    }


}

回答1:


When Java performs overload resolution for choosing methods, it uses that type of the variable, not the runtime type of the object, to choose the method. The type of x is Bird, so the Third method chosen is foo(Bird).

This is because polymorphism isn't involved here; we're not calling a potentially overridden method on the Bird variable x, we're just calling one of a set of overloaded methods on an unrelated class, Third.




回答2:


At compile time, method invocation for overloaded methods is determined based on the type the method parameters and the compile time (or static) type of the method arguments.

In your case, Third#foo(..) can take a Hawk and it can take a Bird. In your invocation

y.foo(x);

the compile time (or static) type of the argument x is Bird, since that's how it's declared, so the Third#foo(Bird) method will be invoked.



来源:https://stackoverflow.com/questions/23001314/java-method-overload-inheritance-and-polymorphism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!