views:

64

answers:

3

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.

A: 

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.

foret
Absolutely incorrect. I'll save you the burden of downvoting this answer.
The Elite Gentleman
Why not? Explain please, if you have smth to say.
foret
See my post....
The Elite Gentleman
i didn't read the whole question carefully. In your case, you don't need to add anything - there will be an error, because AnObject cannot be subclass of String.
foret
I still don't see error in my post, except in PS, where i didn't know about AnObject. The principle is still the same.
foret
`if you add constructor (InputStream) , compiler will throw error because of ambiguety`. How does that apply to the example provided by the OP?
The Elite Gentleman
@foret - Correct or not, it does not answer "If I pass null to the constructor, which constructor is chosen and why?", the essence of your answer "the most specific contructor it can find", helps nothing? How is one class more specific to null??
Ishtar
+2  A: 

By doing this:

ConstructorTest test = new ConstructorTest(null);

The compiler will complain stating:

The constructor ConstructorTest(AnObject) is ambiguous.

It doesn't understand which constructor it needs to call.

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

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

or

ConstructorTest test = new ConstructorTest((AnObject)null);
The Elite Gentleman
You are right, I made a mistake in my test, that's why the compiler error didn't show up.
Mano Swerts
+2  A: 

The compiler will generate error.

heximal
You should elaborate further.
The Elite Gentleman
You are right, I made a mistake in my test, that's why the compiler error didn't show up.
Mano Swerts