本文介绍了java方法重载继承和多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到的测试练习题,非常感谢您帮助我理解概念

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

让Hawk成为Bird的子类。假设某个类有两个重载方法void foo(Hawk
h)和void foo(Bird b)。在
声明之后调用foo(x)中将执行哪个版本Bird x = new Hawk();

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

这是我到目前为止的代码,有人可以向我解释为什么foo(鸟b)被执行?

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");
    }


}


推荐答案

当Java为选择方法执行重载决策时,它使用该类型的变量而不是对象的运行时类型来选择方法。 x 的类型是 Bird ,所以第三方法选择 foo(Bird)

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

这是因为此处不涉及多态性;我们没有在 Bird 变量 x 上调用可能被重写的方法,我们只是调用一个集合中的一个不相关类的重载方法,第三

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.

这篇关于java方法重载继承和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 19:29