定义长方形类Rectangle,含属性: int width; int height。方法:Rectangle():宽、高默认值为1;Rectangle(int val):宽、高均为参数值;Rectangle(int width,int height):Double getSquare():计算面积;Double getPerimeter():计算周长。另外编写测试类进行测试。
时间: 2024-02-20 09:02:21 浏览: 44
好的,以下是 Rectangle 类的定义和测试代码:
```java
public class Rectangle {
private int width;
private int height;
public Rectangle() {
this.width = 1;
this.height = 1;
}
public Rectangle(int val) {
this.width = val;
this.height = val;
}
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public double getSquare() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
```
测试代码:
```java
public class RectangleTest {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
System.out.println("r1: width=" + r1.width + ", height=" + r1.height);
System.out.println("r1 square=" + r1.getSquare() + ", perimeter=" + r1.getPerimeter());
Rectangle r2 = new Rectangle(5);
System.out.println("r2: width=" + r2.width + ", height=" + r2.height);
System.out.println("r2 square=" + r2.getSquare() + ", perimeter=" + r2.getPerimeter());
Rectangle r3 = new Rectangle(3, 4);
System.out.println("r3: width=" + r3.width + ", height=" + r3.height);
System.out.println("r3 square=" + r3.getSquare() + ", perimeter=" + r3.getPerimeter());
}
}
```
输出结果:
```
r1: width=1, height=1
r1 square=1.0, perimeter=4.0
r2: width=5, height=5
r2 square=25.0, perimeter=20.0
r3: width=3, height=4
r3 square=12.0, perimeter=14.0
```
注意,这里的周长和面积都是 double 类型的,而不是 int 类型。
阅读全文