Here when I run this below code I get called as the output and I was wondering why not called new. Since 1 comes under both short and int range.
public class MyClass {
private int x;
public MyClass(){
this(1);
}
public MyClass(int x){
System.out.println("called");
this.x = x;
}
public MyClass(short y){
System.out.println("called new");
this.x = y;
}
public static void main(String args[]) {
MyClass m = new MyClass();
System.out.println("hello");
}
}
1is anintliteral, soMyClass(int x)is chosen.Even if you remove the
MyClass(int x)constructor,MyClass(short y)won't be chosen. You'll get a compilation error instead, since1is notshort.You'll have to cast
1to short -this((short)1);- in order for theMyClass(short y)to be chosen.