设计一个名为 Rectangle 的类表示矩形 定义两个属性: double width 和 double height 分别表示宽和高,默认都为 1 创建默认举行的无参构造方法 使用指定宽和高创建矩形对象的构造方法 一个名为 getArea 的返回矩形
时间: 2024-05-08 18:20:44 浏览: 25
的面积的方法,公式为面积 = 宽 * 高,一个名为 getPerimeter 的返回矩形的周长的方法,公式为周长 = 2 * (宽 + 高)。
下面是实现该类的示例代码:
```java
public class Rectangle {
private double width;
private double height;
public Rectangle() {
this.width = 1;
this.height = 1;
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return this.width * this.height;
}
public double getPerimeter() {
return 2 * (this.width + this.height);
}
}
```
可以通过以下方式创建并使用矩形对象:
```java
Rectangle defaultRectangle = new Rectangle(); // 宽和高都为 1 的默认矩形
Rectangle customRectangle = new Rectangle(3, 4); // 宽为 3,高为 4 的自定义矩形
double area = defaultRectangle.getArea(); // 获取默认矩形的面积
double perimeter = customRectangle.getPerimeter(); // 获取自定义矩形的周长
```