7.1(Rectangle类)按照第7.2节中Circle类的例子,设计一个名为Rectangle类来表示矩形。这个类 包括: ●两个名为width和height的数据域。 构造方法创建一个指定width和heightd的矩形。将1和2分别作为width和height的默认值。一个名为getArea)的方法来返回这个矩形的面积。一个名为getPerimeter)的方法返回周长。 绘制该类的UML类图,然后实现这个类。编写一个测试程序创建两个Rectangle对象,一个宽为4高为40,而另一个宽为3.5高为35.7。按照这个顺序显示每个矩形的宽、高、面积和周长。
时间: 2023-12-14 12:36:18 浏览: 72
以下是Rectangle类的UML类图:
```
------------------------------------
| Rectangle |
------------------------------------
| - width: double |
| - height: double |
------------------------------------
| + Rectangle() |
| + Rectangle(width: double, height: double)|
| + getArea(): double |
| + getPerimeter(): double |
------------------------------------
```
以下是Rectangle类的实现:
```java
public class Rectangle {
private double width;
private double height;
public Rectangle() {
this.width = 1;
this.height = 2;
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
```
以下是测试程序:
```java
public class RectangleTest {
public static void main(String[] args) {
Rectangle rectangle1 = new Rectangle(4, 40);
Rectangle rectangle2 = new Rectangle(3.5, 35.7);
System.out.println("Rectangle 1:");
System.out.println("Width: " + rectangle1.getWidth());
System.out.println("Height: " + rectangle1.getHeight());
System.out.println("Area: " + rectangle1.getArea());
System.out.println("Perimeter: " + rectangle1.getPerimeter());
System.out.println("\nRectangle 2:");
System.out.println("Width: " + rectangle2.getWidth());
System.out.println("Height: " + rectangle2.getHeight());
System.out.println("Area: " + rectangle2.getArea());
System.out.println("Perimeter: " + rectangle2.getPerimeter());
}
}
```
输出结果:
```
Rectangle 1:
Width: 4.0
Height: 40.0
Area: 160.0
Perimeter: 88.0
Rectangle 2:
Width: 3.5
Height: 35.7
Area: 124.95000000000002
Perimeter: 78.4
```
阅读全文