了解选择哪个构造函数以及原因 [英] Understanding which constructor is chosen and why
问题描述
为什么每次打印时都会关注程序我是字符串
而不是我是对象。
或我是int。
?
Why following program every time prints I'm string
and not I'm object.
or I'm int.
?
public class Demo {
public Demo(String s){
System.out.println("I'm string");
}
public Demo(int i){
System.out.println("I'm int.");
}
public Demo(Object o){
System.out.println("I'm object.");
}
public static void main(String[] args) {
new Demo(null);
}
}
此外,如果我替换 int
,整数
。它给出错误构造函数Demo(String)不明确。
为什么?
Also if I replace int
with Integer
. It gives error as The constructor Demo(String) is ambiguous.
Why?
推荐答案
null
可以转换为对象
或字符串
,但不是 int
。因此第二个构造函数已经出局。
null
can be converted to Object
or String
, but not int
. Therefore the second constructor is out.
在转换为对象
或转换为之间字符串
,转换为字符串
更具体,所以这就是所选择的。
Between the conversion to Object
or the conversion to String
, the conversion to String
is more specific, so that's what's picked.
JLS 第15.12.2节描述了方法超载分辨率,我相信相同的方法用于构造函数解析。 第15.12.2.5节介绍了如何选择最具体的内容方法(在这种情况下为构造函数):
The JLS section 15.12.2 describes method overload resolution, and I believe the same approach is used for constructor resolution. Section 15.12.2.5 describes choosing the most specific method (constructor in this case):
非正式的直觉是,如果第一种方法处理任何调用,则一种方法比另一种方法更具体可以在没有编译时类型错误的情况下传递给另一个。
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.
这是关于使用Object或String参数的构造函数调用 - 由 new Demo(String)
处理的任何调用也可以传递给 new Demo(Object)
而无需编译 - 时间类型错误,但相反的是不为真,因此新的演示(字符串)
一个更具体......因此由重载决策规则。
This about the constructor invocation with Object or String arguments - any invocation handled by new Demo(String)
could also be passed on to new Demo(Object)
without a compile-time type error, but the reverse is not true, therefore the new Demo(String)
one is more specific... and thus chosen by the overload resolution rules.
这篇关于了解选择哪个构造函数以及原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!