Java 如何在 "explicit constructor invocation" 期间区分几乎相同的构造函数?
How does Java differantiate between almost identical constructors during "explicit constructor invocation"?
我正在阅读 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 的类型。我的问题是,为什么它不转到我写的第三个构造函数(具有 'short' 类型)或给出错误。当我打印出对象的 'x' 值时,我总是得到 0 而不是 4。Java 如何决定使用 'int'?
In the default constructor, "this(0,0,1,1);" line doesn't specify the types of the 0s
这是一个不正确的陈述。整型数字文字(没有后缀)总是 int
(这就是为什么像 3000000000
这样的文字会出现编译错误,因为该值对于 int
来说太大了)。因此,最后一个构造函数 - Rectangle(int x, int y, int width, int height)
- 被选中。
我正在阅读 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 的类型。我的问题是,为什么它不转到我写的第三个构造函数(具有 'short' 类型)或给出错误。当我打印出对象的 'x' 值时,我总是得到 0 而不是 4。Java 如何决定使用 'int'?
In the default constructor, "this(0,0,1,1);" line doesn't specify the types of the 0s
这是一个不正确的陈述。整型数字文字(没有后缀)总是 int
(这就是为什么像 3000000000
这样的文字会出现编译错误,因为该值对于 int
来说太大了)。因此,最后一个构造函数 - Rectangle(int x, int y, int width, int height)
- 被选中。