java - Java 如何在 "explicit constructor invocation"期间区分几乎相同的构造函数?

标签 java constructor constructor-overloading

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

最佳答案

In the default constructor, "this(0,0,1,1);" line doesn't specify the types of the 0s

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

关于java - Java 如何在 "explicit constructor invocation"期间区分几乎相同的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49166940/

相关文章:

c++ - 如何在嵌套列表初始化中从 map<> 中辨别 vector<>?

c# - 如何验证重载构造函数的输入?

java - 为 Bukkit 插件添加颜色代码支持

Java - 遍历 ArrayList 的问题

c++ - 数组对象初始化,其类具有一些 ctor/dtor

java - 子类构造函数

java - 获取recyclerview中的按钮状态

java - Liferay - 调度程序未在给定时间触发

types - 参数较少的外部构造函数

c++ - 具有类似转换的枚举、构造函数重载