定义一个矩形类,类里包含长、宽、周长、面积四个属性,计算周长和面积的方法各一个,编写测试类,利用矩形类申明两个对象并进行初始化,分别初始化长和宽,然后计算这两个矩形的面积和周长,通过屏幕打印出来。
时间: 2024-03-11 19:19:48 浏览: 73
好的,这是一个关于 Java 编程的问题。下面是代码实现:
```java
public class Rectangle {
// 成员变量
private double length;
private double width;
private double perimeter;
private double area;
// 构造方法
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
this.perimeter = 2 * (length + width);
this.area = length * width;
}
// 计算周长
public double getPerimeter() {
return perimeter;
}
// 计算面积
public double getArea() {
return area;
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(3, 4);
Rectangle r2 = new Rectangle(5, 6);
System.out.println("The perimeter of r1 is: " + r1.getPerimeter());
System.out.println("The area of r1 is: " + r1.getArea());
System.out.println("The perimeter of r2 is: " + r2.getPerimeter());
System.out.println("The area of r2 is: " + r2.getArea());
}
}
```
以上程序输出应该为:
```
The perimeter of r1 is: 14.0
The area of r1 is: 12.0
The perimeter of r2 is: 22.0
The area of r2 is: 30.0
```
阅读全文