null is a reference and is of type only null , i.e. null not an object type. But when I run the following code snippet, I was surprised to pass null to method(null); , it calls method(String s) not method(Object o) .
If null itself is a type defined by Java, not an 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 added another method:
public static void method(Integer s) { System.out.println("String impl11"); }
Now the compiler throws an error The method method(Object) is ambiguous for the type Test .
Integer a = null;
If this is legal, then why do I see an exception at compile time?
java object oop
Priya
source share