null
is a reference and it is of null
type only, i.e. null
is not object type.
But, when I run the following code snippet I was surprised when I pass null to method method(null);
it calls method(String s)
not method(Object o)
.
If null
is itself a type defined by Java and not object type, then why does it call method(String s)
not method(Object o)
?
public class Test {
public static void main(String[] args) {
method(null);
}
public static void method(Object o) {
System.out.println("Object impl");
}
public static void method(String s) {
System.out.println("String impl");
}
}
Edit
I have added one more method:
public static void method(Integer s) {
System.out.println("String impl11");
}
Now the compiler gives the error The method method(Object) is ambiguous for the type Test
.
Integer a = null;
If it is legal, then why do I see a compile-time exception?