二、设计一个名为Rectangle的类表示矩形:e 成员变量:长度 width、宽度 heigh, double 型;一 构造方法: 默认知形的无参构造方法,width和height的默认值为1: width和 height为指定值的矩形的构造方法;一 ·方法:4 getArea (),返回这个矩形的面积;e getPerimeter (),方法返回周长;℃其它:心 编写一个测试程序:4 创建两个Rectangle对象,一个矩形R1的长为20,宽为5; 另一个矩形R2的长为25,宽为6;4 按照这个顺序显示每个矩形的长、宽、面积和周长。
时间: 2024-02-03 21:14:35 浏览: 33
下面是实现了上述需求的 Rectangle 类及测试程序的代码:
```java
public class Rectangle {
private double width;
private double height;
public Rectangle() {
width = 1;
height = 1;
}
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 r1 = new Rectangle(20, 5);
Rectangle r2 = new Rectangle(25, 6);
System.out.println("Rectangle 1:");
System.out.println("Width: " + r1.width);
System.out.println("Height: " + r1.height);
System.out.println("Area: " + r1.getArea());
System.out.println("Perimeter: " + r1.getPerimeter());
System.out.println();
System.out.println("Rectangle 2:");
System.out.println("Width: " + r2.width);
System.out.println("Height: " + r2.height);
System.out.println("Area: " + r2.getArea());
System.out.println("Perimeter: " + r2.getPerimeter());
}
}
```
输出结果:
```
Rectangle 1:
Width: 20.0
Height: 5.0
Area: 100.0
Perimeter: 50.0
Rectangle 2:
Width: 25.0
Height: 6.0
Area: 150.0
Perimeter: 62.0
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)