为什么Java喜欢调用双重构造函数? [英] Why does Java prefer to call double constructor?
问题描述
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);
}
}
在上面的代码中,我传递 null
作为构造函数参数。因为 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
推荐答案
原因是Java将任何类型解释为 null
,当选择要调用的方法时,它将选择最具体的方法类型。因为 null
可以是 double []
和 double []
是 Object
,编译器将选择采用 double []
的方法。如果选择涉及同样可能但不相关的类型,例如 double []
和 String
,那么编译器将无法选择一个方法,模糊方法调用错误。
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.
JLS,第4.1节,说明:
空引用总是可以分配或转换任何引用类型(§5.2,§5.3,§5.5)。
The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).
在实践中,程序员可以忽略null类型,只是假设null只是一个特殊的字面量可以是任何引用类型。
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.
这篇关于为什么Java喜欢调用双重构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!