在下面的示例中,我有 2 个构造函数:一个采用 String,另一个采用自定义对象。在此自定义对象上存在一个方法“getId()”,该方法返回一个字符串。
public class ConstructorTest {
private String property;
public ConstructorTest(AnObject property) {
this.property = property.getId();
}
public ConstructorTest(String property) {
this.property = property;
}
public String getQueryString() {
return "IN_FOLDER('" + property + "')";
}
}
如果我将 null 传递给构造函数,会选择哪个构造函数,为什么?在我的测试中,选择了 String 构造函数,但我不知道是否总是如此以及为什么。
我希望有人能为我提供一些对此的见解。
提前致谢。
通过做这个:
ConstructorTest test = new ConstructorTest(null);
编译器会抱怨说:
构造函数ConstructorTest(AnObject)
是模棱两可的。
JVM 无法选择要调用哪个构造函数,因为它无法识别与构造函数匹配的类型(请参阅:15.12.2.5 选择最具体的方法).
您可以致电specific通过类型转换参数来构造函数,例如:
ConstructorTest test = new ConstructorTest((String)null);
or
ConstructorTest test = new ConstructorTest((AnObject)null);
Update:感谢@OneWorld,可以访问相关链接(撰写本文时最新)here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)