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

时间:2010-10-26 08:03:50

标签: java constructor null

在下面的示例中,我有2个构造函数:一个使用String,另一个使用自定义对象。在此自定义对象上,存在一个返回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构造函数,但我不知道是否总是这样,为什么。

我希望有人可以为我提供一些见解。

提前致谢。

3 个答案:

答案 0 :(得分:15)

通过这样做:

ConstructorTest test = new ConstructorTest(null);

编译器会抱怨说:

  

构造函数ConstructorTest(AnObject)   很暧昧。

JVM无法选择要调用的构造函数,因为它无法识别与构造函数匹配的类型(请参阅:15.12.2.5 Choosing the Most Specific Method)。

您可以通过类型化参数来调用特定构造函数,例如:

ConstructorTest test = new ConstructorTest((String)null);

ConstructorTest test = new ConstructorTest((AnObject)null);

更新:感谢@OneWorld,可以访问相关链接(撰写本文时为最新版本){。{3}}。

答案 1 :(得分:3)

编译器将生成错误。

答案 2 :(得分:0)

Java根据参数使用它可以找到的最具体的构造函数 PS:如果添加构造函数(InputStream),编译器会因为模糊而抛出错误 - 它无法知道更具体的内容:String或InputStream,因为它们位于不同的类层次结构中。

相关问题