Below is the java class having 3 overloaded constructors :
public class Test {
public Test(Object i){
System.out.println(\"Object invoked\");
}
The answer is: Test(String)
is invoked.
Why?
When determining which of a set of overloaded methods will be invoked, the Java compiler will attempt to match the most concrete type. And it will first attempt to match a signature before employing autoboxing. (@arshajii provided a perfect reference into the Java Language Spec on this)
Here, Object
is the most abstract class in the type system. String
subclasses from Object
and is therefore more specific/concrete.
The logic behind this is that if you are overloading a method with a more specific-typed parameter, you're likely wanting to do more with that object (when you subclass, you typically add methods). If method signature determination worked the other way (i.e. the more abstractly-typed signature winning; here, Test(Object)
), then none of the more concrete signatures would ever get called.