【问题标题】:Two constructors having same no. of parameters but different data types两个具有相同编号的构造函数。参数,但不同的数据类型
【发布时间】:2017-11-26 06:54:13
【问题描述】:

当我在下面的代码中运行时,我得到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");
        }
    }

【问题讨论】:

    标签: java multiple-constructors


    【解决方案1】:

    1int 文字,因此选择了 MyClass(int x)

    即使您删除 MyClass(int x) 构造函数,MyClass(short y) 也不会被选中。你会得到一个编译错误,因为1 不是short

    您必须将1 转换为short - this((short)1); - 才能选择MyClass(short y)

    【讨论】:

    • 我不明白 1 怎么不短
    • @Coder17 任何没有后缀的整数数字文字,无论大小,编译器都将其视为int。编译器不会检查 int 文字的值以确定它是否适合 short 变量。编译器进行此类检查的唯一时间是您将 int 文字分配给 short 变量。
    【解决方案2】:

    作为其他答案的补充,我建议您在使用相同的文字初始化其他类型的变量时检查正在调用哪些构造函数:

    short s = 1;
    int i = 1;
    

    然后检查使用上述参数调用MyClass 的哪个构造函数。

    【讨论】:

      猜你喜欢
      • 2010-09-07
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多