Java method dispatch with null argument

Which version of Java are you using? With 1.6.0_11 the code (pasted below) compiles and runs.

I am sure its obvious why foo(testVal) goes to foo(Object).

The reason why foo(null) goes to foo(String) is a little complex. The constant null is of type nulltype, which is a subtype of all types. So, this nulltype extends String, which extends Object.

When you call foo(null) compiler looks for the overloaded method with most specific type. Since String is more specific then Object that is the method that gets called.

If you had another overload that was as specific as String, say foo(Integer) then you would get a ambiguous overload error.

class NullType {

  public static final void main(final String[] args) {
    foo();
  }

  static void foo()
  {
    Object testVal = null;
    foo(testVal);    // dispatched to foo(Object)
    foo(null);    // compilation problem -> "The method foo(String) is ambiguous"   
  }

  public static void foo(String arg) { // More-specific
    System.out.println("foo(String)");
  }

  public static void foo(Object arg) { // Generic
    System.out.println("foo(Object)");
  }

}

Leave a Comment