gpt4 book ai didi

java - 两个具有相同编号的构造函数。参数但不同的数据类型

转载 作者:行者123 更新时间:2023-11-29 07:28:01 26 4
gpt4 key购买 nike

在这里,当我运行下面的代码时,我得到了 called 作为输出,我想知道为什么不 called new。因为 1 属于 shortint 范围。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com