java method overload inheritance and polymorphism -
here's test practice question came across, appreciate in making me understand concepts
let hawk subclass of bird. suppose class has 2 overloaded methods void foo(hawk h) , void foo(bird b). version executed in call foo(x) after declaration bird x = new hawk();
here's code have far, explain 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"); } }
when java performs overload resolution choosing methods, uses type of variable, not runtime type of object, choose method. type of x
bird
, third
method chosen foo(bird)
.
this because polymorphism isn't involved here; we're not calling potentially overridden method on bird
variable x
, we're calling 1 of set of overloaded methods on unrelated class, third
.
Comments
Post a Comment