Which constructor is chosen when passing null?

2020-04-04 16:46发布

In the following example, I have 2 constructors: one that takes a String and one that takes a custom object. On this custom object a method "getId()" exists which returns a String.

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 + "')";
 }
}

If I pass null to the constructor, which constructor is chosen and why? In my test the String constructor is chosen, but I do not know if this will always be the case and why.

I hope that someone can provide me some insight on this.

Thanks in advance.

3条回答
Rolldiameter
2楼-- · 2020-04-04 17:23

By doing this:

ConstructorTest test = new ConstructorTest(null);

The compiler will complain stating:

The constructor ConstructorTest(AnObject) is ambiguous.

The JVM cannot choose which constructor to invoke as it cannot identify the type that matches the constructor (See: 15.12.2.5 Choosing the Most Specific Method).

You can call specific constructor by typecasting the parameter, like:

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

or

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

Update: Thanks to @OneWorld, the relevant link (up to date at the time of writing) can be accessed here.

查看更多
成全新的幸福
3楼-- · 2020-04-04 17:30

Java uses the most specific contructor it can find according to arguments.
PS: if you add constructor (InputStream) , compiler will throw error because of ambiguety - it cannot know what is more specific: String or InputStream, because they are in different class hierarchy.

查看更多
家丑人穷心不美
4楼-- · 2020-04-04 17:34

The compiler will generate error.

查看更多
登录 后发表回答