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)?
That is because
Stringclass extends fromObjectand hence is more specific toObject. So, compiler decides to invoke that method. Remember, Compiler always chooses the most specific method to invoke. See Section 15.12.5 of JLSHowever, if you have two methods with parameter –
String, andInteger, then you would getambiguityerror fornull, as compiler cannot decide which one is more specific, as they are non-covariant types.