Bri*_*acy 1 java constructor this
在 Oracle 提供的在线 Java 教程中,我看到了以下内容。
public class Rectangle {
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(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
Run Code Online (Sandbox Code Playgroud)
前两个构造this()函数使用函数来设置类的实例变量。第三个构造函数不简单地利用this(x,y,width,height).
注意:这是否只是为了显示(在教程设置中)它 this也是一个关键字并且也可以用于设置实例变量?
第三个构造函数不简单地利用 this(x,y,width,height)是否有原因。
因为它是将被调用的构造函数
this(x, y, width, height);
Run Code Online (Sandbox Code Playgroud)
这将导致无限递归循环。
正如Keppil在评论中所说,this是一个关键字。当使用像
this(x, y, width, height);
Run Code Online (Sandbox Code Playgroud)
在构造函数中,它使用适当的参数列表调用类构造函数。在这种情况下,该构造函数是第三个构造函数。所以你的建议是第三个构造函数调用第三个构造函数,它调用第三个构造函数,令人作呕。
| 归档时间: |
|
| 查看次数: |
6257 次 |
| 最近记录: |