java创建矩形类Rectangle,以及测试类RectangleTest
时间: 2024-05-05 09:15:49 浏览: 75
Rectangle类:
```java
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
```
RectangleTest类:
```java
public class RectangleTest {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(4, 6);
System.out.println("Width: " + r1.getWidth());
System.out.println("Height: " + r1.getHeight());
System.out.println("Area: " + r1.getArea());
System.out.println("Perimeter: " + r1.getPerimeter());
r1.setWidth(5);
r1.setHeight(7);
System.out.println("Width: " + r1.getWidth());
System.out.println("Height: " + r1.getHeight());
System.out.println("Area: " + r1.getArea());
System.out.println("Perimeter: " + r1.getPerimeter());
}
}
```
输出结果:
```
Width: 4.0
Height: 6.0
Area: 24.0
Perimeter: 20.0
Width: 5.0
Height: 7.0
Area: 35.0
Perimeter: 24.0
```
阅读全文