在下面的示例中,我有 2 个构造函数:一个接受字符串,另一个接受自定义对象。在这个自定义对象上存在一个返回字符串的方法“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);
编译器会提示说:
The constructor ConstructorTest(AnObject) is ambiguous.
JVM 无法选择调用哪个构造函数,因为它无法识别与构造函数匹配的类型(参见:15.12.2.5 Choosing the Most Specific Method)。
您可以通过对参数进行类型转换来调用特定构造函数,例如:
ConstructorTest test = new ConstructorTest((String)null);
或
ConstructorTest test = new ConstructorTest((AnObject)null);
更新:感谢@OneWorld,可以访问相关链接(在撰写本文时是最新的)here .
关于java - 传递 null 时选择哪个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4021733/