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");
}
}
1
is anint
literal, 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, since1
is notshort
.You'll have to cast
1
to short -this((short)1);
- in order for theMyClass(short y)
to be chosen.