【问题标题】:How does Java differantiate between almost identical constructors during "explicit constructor invocation"? [duplicate]在“显式构造函数调用”期间,Java 如何区分几乎相同的构造函数? [复制]
【发布时间】:2018-03-08 06:42:24
【问题描述】:

我正在阅读 Java 教程并且有一个关于显式构造函数调用的问题。首先,这里是教程中写的字段和构造函数,加上我添加的另一个构造函数:

private int x, y;
private int width, height;

public Rectangle() {
    this(0, 0, 1, 1);
}

public Rectangle(int width, int height) {
    this(0, 0, width, height);
}

public Rectangle(short x, short y, int width, int height) {
    this.x = (int) x+4;
    this.y = (int) y+4;
    this.width = width;
    this.height = height;
}

public Rectangle(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

在默认构造函数中,“this(0,0,1,1);”行没有指定 0 的类型。我的问题是,为什么它不转到我编写的第三个构造函数(使用“短”类型)或给出错误。当我打印出对象的 'x' 值时,我总是得到 0 而永远不会得到 4。Java 是如何决定使用 'int' 的?

【问题讨论】:

    标签: java constructor constructor-overloading


    【解决方案1】:

    在默认构造函数中,“this(0,0,1,1);”行没有指定 0 的类型

    这是一个错误的说法。整数数字文字(没有后缀)总是ints(这就是为什么像3000000000 这样的文字会是编译错误,因为对于int 来说该值太大了)。因此选择了最后一个构造函数 - Rectangle(int x, int y, int width, int height)

    【讨论】:

    • 好的,但是当我将默认构造函数修改为“this((short) 0, (short) 0, 1, 1);”时它仍然转到最后一个构造函数。
    • @DerivedEngineer no,this( (short) 0, (short) 0, 1, 1) 将调用 Rectangle(short x, short y, int width, int height) 构造函数。你一定是搞错了。
    • 是的,我的错。谢谢。
    猜你喜欢
    • 2013-08-14
    • 2016-12-09
    • 2017-07-28
    • 2012-07-13
    • 2015-02-25
    • 1970-01-01
    • 2019-08-07
    • 2012-02-28
    相关资源
    最近更新 更多