Given I have a class with two constructors:
public class TestClass {
ObjectOne o1;
ObjectTwo o2;
public TestClass(ObjectOne o1) {
// ..
}
public TestClass(ObjectTwo o2) {
// ..
}
}
Please assume, that ObjectOne is an interface type, and ObjectTwo implements ObjectOne. What happens, if I call:
new TestClass(null);
How to determine the correct method to call? And who determines that?
Are there differences between Java and other OOP languages?
This question is really about resolving ambiguous overloads, and not really about run-time polymorphism (because choosing which overloaded method to invoke is done at compile-time).
Method resolution is a complicated thing, and in this case, whether or not the code compiles at all does depend on what the types involved are. There are plenty of situations in which the code will compile. See code below (note that
String implements CharSequence):Note that without the cast, the
Stringoverload is chosen. This is exactly as specified in JLS:JLS 15.12.2.5 Choosing the Most Specific Method
A
Stringis-aCharSequence, but not allCharSequenceis-aString. Therefore,Stringis more specific thanCharSequence, hence why theStringoverload is chosen in the above example.It is worth noting that this exact question (in essence) appeared in the wonderful Java Puzzlers (highly recommended), specifically Puzzle 46: The Case of the Confusing Constructor
I will close with a quote from Effective Java 2nd Edition, Item 41: Use overloading judiciously:
Needless to say, this book is also highly recommended.
See also