Zero has a reference type, is a reference to a String or an Object a reference?

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?

+7
java object oop
source share
1 answer

null assigned to any reference type. When it comes to method overloading, the compiler always prefers a method with more specific types of arguments. Therefore, a method with an argument of String preferable to a method with an argument of Object , since String is a subclass of Object .

If, on the other hand, the choice was between methods with unrelated types of arguments - for example, method(String s) and method (Integer i) - the code did not pass compilation, since none of the parameters would have priority over the other.

+11
source share

All Articles