gpt4 book ai didi

java - 传递 null 时选择哪个构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:29 24 4
gpt4 key购买 nike

在下面的示例中,我有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com