[英]Two constructors having same no. of parameters but different data types
Here when I run this below code I get called
as the output and I was wondering why not called new
. 在这里,当我运行下面的代码时,我被
called
输出,我想知道为什么不called new
。 Since 1 comes under both short
and int
range. 由于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
is an int
literal, so MyClass(int x)
is chosen. 1
是int
常量,因此选择MyClass(int x)
。
Even if you remove the MyClass(int x)
constructor, MyClass(short y)
won't be chosen. 即使删除
MyClass(int x)
构造函数,也不会选择MyClass(short y)
。 You'll get a compilation error instead, since 1
is not short
. 相反,您会收到编译错误,因为
1
short
。
You'll have to cast 1
to short - this((short)1);
您必须将
1
为short- this((short)1);
- in order for the MyClass(short y)
to be chosen. -为了选择
MyClass(short y)
。
As an addition to others answer I can suggest you to check which constructors are being called when you initialize variables of other types using the same literal: 作为其他答案的补充,我建议您使用相同的文字初始化其他类型的变量时,检查正在调用哪些构造函数:
short s = 1;
int i = 1;
And then check which constructor of MyClass
is being called as you call them with above arguments. 然后在使用上述参数调用
MyClass
检查正在调用哪个MyClass
构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.