Why following program every time prints I'm string and not I'm object. or I'm int.?
public class Demo {
public Demo(String s){
System.out.println("I'm string");
}
public Demo(int i){
System.out.println("I'm int.");
}
public Demo(Object o){
System.out.println("I'm object.");
}
public static void main(String[] args) {
new Demo(null);
}
}
Also if I replace int with Integer. It gives error as The constructor Demo(String) is ambiguous. Why?
nullcan be converted toObjectorString, but notint. Therefore the second constructor is out.Between the conversion to
Objector the conversion toString, the conversion toStringis more specific, so that’s what’s picked.The JLS section 15.12.2 describes method overload resolution, and I believe the same approach is used for constructor resolution. Section 15.12.2.5 describes choosing the most specific method (constructor in this case):
This about the constructor invocation with Object or String arguments – any invocation handled by
new Demo(String)could also be passed on tonew Demo(Object)without a compile-time type error, but the reverse is not true, therefore thenew Demo(String)one is more specific… and thus chosen by the overload resolution rules.