简体   繁体   English

两个构造器具有相同的编号。 参数,但数据类型不同

[英]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属于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 is an int literal, so MyClass(int x) is chosen. 1int常量,因此选择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.

相关问题 同一类中的两个构造函数具有不同的参数 - Two constructors at in the same class with different parameters Kotlin - 无法创建两个具有不同列表类型参数的构造函数 - Kotlin - Can't create two constructors with different List types parameters 两个构造函数执行不同的操作但采用相同的数据类型 - Two constructors that do different things but take the same data type Spring DI同时具有两个构造函数 - Spring DI having two constructors at the same time 根据同一方法的条件返回两种不同的数据类型 - Return two different data types based on condition from the same method Java 多个 inheritance 使用两个接口,方法相同但参数不同 - Java multiple inheritance using two interface having same method but different parameters 如何在同一个类中创建两个不同的构造函数 - Android - How to make two different Constructors in the same Class - Android 我如何创建3个超抽象类,它们已经在构造函数中提供了数量不同的相似子类 - How can i create a super abstract class of 3 already present similar subclasses having different number of parameters in their constructors 关于拥有java的各种构造函数和参数 - About having various constructors and parameters for java Extends 和 Interface 具有相同的方法,但具有相同的参数但不同的返回类型 - Extends and Interface has same method with the same parameters but different return types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM