Java method dispatch with null argument

前端 未结 4 1385
孤独总比滥情好
孤独总比滥情好 2020-11-27 08:38

Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value

4条回答
  •  执笔经年
    2020-11-27 09:08

    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)");
      }
    
    }
    

提交回复
热议问题