Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Java null behavior in Method Overloading [duplicate]

I have the following code snippet:

public static void foo(Object x) {
    System.out.println("Obj");
}
public static void foo(String x) {
    System.out.println("Str");
}

If I call foo(null) why is there no ambiguity? Why does the program call foo(String x) instead of foo(Object x)?

like image 439
dreamcrash Avatar asked Feb 09 '13 15:02

dreamcrash


2 Answers

why the program calls foo(String x) instead of foo(Object x)

That is because String class extends from Object and hence is more specific to Object. So, compiler decides to invoke that method. Remember, Compiler always chooses the most specific method to invoke. See Section 15.12.5 of JLS

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

However, if you have two methods with parameter - String, and Integer, then you would get ambiguity error for null, as compiler cannot decide which one is more specific, as they are non-covariant types.

like image 118
Rohit Jain Avatar answered Sep 27 '22 18:09

Rohit Jain


  1. The type of null is by definition a subtype of every other reference type. Quote JLS 4.1:

    The null reference can always undergo a widening reference conversion to any reference type.

  2. The resolution of the method signature involved in an invocation follows the principle of the most specific signature in the set of all compatible signatures. (JLS 15.12.2.5. Choosing the Most Specific Method).

Taken together this means that the String overload is chosen in your example.

like image 25
Marko Topolnik Avatar answered Sep 27 '22 20:09

Marko Topolnik