Strange Java null behavior in Method Overloading -


this question has answer here:

i have following code snippet:

public static void foo(object x) {     system.out.println("obj"); } public static void foo(string x) {     system.out.println("str"); } 

if call foo(null) why there no ambiguity? why program call foo(string x) instead of foo(object x)?

why program calls foo(string x) instead of foo(object x)

that because string class extends object , hence more specific object. so, compiler decides invoke method. remember, compiler chooses specific method invoke. see section 15.12.5 of jls

if more 1 member method both accessible , applicable method invocation, necessary choose 1 provide descriptor run-time method dispatch. java programming language uses rule specific method chosen.

the informal intuition 1 method more specific if invocation handled first method passed on other 1 without compile-time type error.

however, if have 2 methods parameter - string, , integer, ambiguity error null, compiler cannot decide 1 more specific, non-covariant types.


Comments