7

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?

g t
  • 7,287
  • 7
  • 50
  • 85
Priya
  • 165
  • 1
  • 1
  • 12

1 Answers1

11

null is assignable to any reference type. When it comes to method overloading, the compiler always prefers the method with the more specific argument types. Therefore the method with the String argument is preferred over the method with the Object argument, since String is a sub-class of Object.

If, on the other hand, the choice was between methods with unrelated argument types - for example method(String s) and method (Integer i) - the code wouldn't pass compilation, since none of the options would have precedence over the other.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • @Priya I already edited the answer to address your edit. – Eran Feb 12 '15 at 09:37
  • means `String`, `Integer` ..... are subclases of object class that's why compiler confused which method to call, is it right? – Priya Feb 12 '15 at 09:40
  • @Priya neither String is a sub-class of Integer nor Integer a sub-class or String. Therefore, the compiler has no preference between the two. – Eran Feb 12 '15 at 09:43
  • Thanks for answering to my quation. – Priya Feb 12 '15 at 09:45