java method overload inheritance and polymorphism

后端 未结 2 1672
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 15:41

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 tw

相关标签:
2条回答
  • 2021-01-25 16:33

    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.

    0 讨论(0)
  • 2021-01-25 16:33

    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.

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