在这里,当我运行下面的代码时,我得到了 called
作为输出,我想知道为什么不 called new
。因为 1 属于 short
和 int
范围。
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
是一个 int
字面量,因此选择了 MyClass(int x)
。
即使您删除了 MyClass(int x)
构造函数,也不会选择 MyClass(short y)
。你会得到一个编译错误,因为 1
不是 short
。
您必须将 1
转换为 short - this((short)1);
- 为了 MyClass(short y)
被选择。
关于java - 两个具有相同编号的构造函数。参数但不同的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493753/