在Oracle提供的在线Java教程中,我看到了以下内容。在构造函数中使用this()
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;
}
...
}
前两个contructors使用this()
功能设置类的实例变量。 第三个构造函数不是简单地使用this(x,y,width,height)
是否有原因。
注意:这仅仅是显示(在教程设置中)this
也是一个关键字,也可以用来设置实例变量?
'this()'不是设置实例变量的关键字,它用于调用当前对象的其他构造函数。 – Keppil