Why does Java prefer to call double constructor?

痞子三分冷 提交于 2019-12-21 07:16:04

问题


public class test {
    test(double[] a)
    {
        System.out.println("in double");
    }
    test(Object a)
    {
        System.out.println("in object");
    }
    public static void main(String args[])
    {
        new test(null);
    }
}

In the above code, I pass null as the constructor argument. As null can be anything, the above code compiles fine. When I run the code I expected it to print in object but it prints in double What is the reason behind this?

NOTE the linked question may not be duplicate because this question is related with primitive datatype vs Object


回答1:


The reason is that Java interprets null as any type, and when choosing the method to invoke, it will choose the most specific method that first the argument types. Because null can be of the type double[] and a double[] is an Object, the compiler will choose the method that takes a double[]. If the choices involved equally possible yet unrelated types, e.g. double[] and String, then the compiler would not be able to choose a method, and that would result in an ambiguous method call error.

The JLS, Section 4.1, states:

The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).

In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.




回答2:


Both constructors are applicable, because null is convertible to both Object and double[] - so the compiler needs to use overload resolution to determine which constructor to call.

JLS 15.9.3 uses JLS 15.12.2 to determine the "most specific" constructor signature to use, based on which constructor has the most specific parameter types, according to JLS 15.12.2.5. The exact details are slightly obscure (IMO) but in this case the basic rule of thumb of "if you can convert from T1 to T2, but not T2 to T1, then T1 is more specific" is good enough.

double[] is a more specific type than Object, because there's an implicit conversion from double[] to Object, but not vice versa.



来源:https://stackoverflow.com/questions/30850695/why-does-java-prefer-to-call-double-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!