Java method dispatch with null argument

前端 未结 4 1397
孤独总比滥情好
孤独总比滥情好 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:15

    Sorry to use an answer, for a comment, but I need to post code that won't fit in comment.

    @Yang, I am also able to compile and run the following. Can you post a complete code that compiles with one line commented such that if I uncomment that line it won't compile?

    class NullType {
    
      public static final void main(final String[] args) {
        foo();
        new Test().bar(new Test());
      }
    
      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(Integer arg) { // More-specific
        System.out.println("foo(Integer)");
      }
    
      public static void foo(Object arg) { // Generic
        System.out.println("foo(Object)");
      }
    
    
    }
    
    
    class Test
    {
      void bar(Test test)
      {
        Object testVal = null;
        test.foo(testVal);    // dispatched to foo(Object)
        test.foo(null);    // compilation problem -> "The method foo(String) is ambiguous"   
      }
    
      public void foo(String arg) { // More-specific
        System.out.println("foo(String)");
      }
    
      public void foo(Object arg) { // Generic
        System.out.println("foo(Object)");
      }
    }
    

提交回复
热议问题