0

我正在阅读 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”的?

4

1 回答 1

1

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

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

于 2018-03-08T06:43:55.773 回答