Method overload selection with null

后端 未结 2 1775
长情又很酷
长情又很酷 2021-01-13 22:13

Given this code:

class Overloading
extends Object
{

static public void target(Object val, String chk) { System.out.println(\"Object[\"+val+\"] :: Should be          


        
相关标签:
2条回答
  • 2021-01-13 22:43

    Remember that the literal null is of type "special null type", not of type Object

    A common confusion is that the literal null is of type Object, thus leading people to believe the closest matched signature is target(Object val, String chk).

    The literal null is actually of type "[special null type]" (Java Language Spec (JLS) 4). If it were possibly to define such a method, the closest match would be target([special null type] val, String chk).

    However, since there isn't such a method (you couldn't create one), the compiler looks for the closest match through subtyping (JLS 15.12.2.2). The direct supertype of the [special null type] are all reference types (JLS 4.10.2) (e.g. String) and Object is a supertype of String.


    Perhaps a more intuitive way to look at it is via the JLS's intuitive definition for the "most specific method" (JLS 15.12.2.5):

    "The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error."

    Of the two methods that the call target(null ,"Object") matches, any call to

    void target(String val, String chk)
    

    could be handled by

    void target(Object val, String chk)
    

    so intuitively void target(String val, String chk) is the "most specific" that could be called without a type error.

    See the JLS 15.12.2.5 for how the "most specific" is formally defined.

    0 讨论(0)
  • 2021-01-13 23:08

    Java has always worked the same way: the "most specific" applicable overload is always chosen. Since String is a subclass of Object, it is "more specific", and the String overload is chosen. If the overloads were for, say String and Integer, and you tried to pass null, then you would indeed get a compile-time ambiguity error, since they are both at the same level of the same inheritance hierarchy.

    0 讨论(0)
提交回复
热议问题