When I run this code it prints String
. My question is why there is no compile time error?
Default value of Object and as well as String is null. Then why not compiler says Reference to method1 is ambiguous
.
public class Test11
{
public static void method1(Object obj) {
System.out.println("Object");
}
public static void method1(String str) {
System.out.println("String");
}
public static void main(String[] arr ) {
method1(null);
}
}
From this answer:
There, you will notice that this is a compile-time task. The JLS says in subsection 15.12.2:
This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable There may be more than one such method, in which case the most specific one is chosen.
The compiler will look at all the possible overloads of the method that could match the parameters you pass. If one of them is more specific than all the others then it will be chosen, it's only considered ambiguous if there is no single most specific overload.
In your example there are two possible overloads, method1(Object)
and method1(String)
. Since String
is more specific than Object
there's no ambiguity, and the String
option will be chosen. If there were a third overload such as method1(Integer)
then there is no longer a single most specific choice for the call method1(null)
, and the compiler would generate an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With