这是java中典型的构造函数的使用方法
1. 首先定义了四个成员变量
2. x, y 表示坐标, width, height 表示宽度和高度
3. 我们知道成员变量在声明类的时候, 会赋予初始值. 案例中的成员变量都是整形, 所以初始值为0
1. 首先定义了四个成员变量
2. x, y 表示坐标, width, height 表示宽度和高度
3. 我们知道成员变量在声明类的时候, 会赋予初始值. 案例中的成员变量都是整形, 所以初始值为0
4. 第一个定义的无参的成员变量调用了带有两个参数的成员变量, 而第二个带有两个参数的成员变量又调用了第三个带有四个参数的成员变量. 这种调用方法, 不但减少了代码量, 提高了代码的复用性, 也确保了多种类的声明方式, 无参数, 有参数都囊括了
class Rectangle {
private int x;
private int y;
private int width;
private int height;
//1st constructor
public Rectangle() {
this(0, 0) ;
}
//2nd constructor
public Rectangle(int width, int height ) {
this(0, 0, width, height);
}
//3rd constructor
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}