定义一个Rectangle类表示矩形。 其中含有length、width这两个double型的private成员变量表示矩形的长和宽。 定义一个无参数的构造方法Rectangle( ), 定义一个有参数的构造方法Rectangle (double length, double width )。 为length和width定义访问方法和修改方法。 定义求矩形周长的方法getPerimeter( ),求矩形面积方法getArea( )。 编写程序测试矩形类的所有方法。
时间: 2024-02-27 11:58:30 浏览: 104
广工java程序语言设计
好的,我明白了,以下是实现矩形类的代码示例:
```java
public class Rectangle {
private double length;
private double width;
public Rectangle() {
this.length = 0.0;
this.width = 0.0;
}
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public double getArea() {
return length * width;
}
}
```
使用以下代码进行测试:
```java
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
System.out.println("Length: " + r1.getLength()); // 0.0
System.out.println("Width: " + r1.getWidth()); // 0.0
System.out.println("Perimeter: " + r1.getPerimeter()); // 0.0
System.out.println("Area: " + r1.getArea()); // 0.0
Rectangle r2 = new Rectangle(5.0, 3.0);
System.out.println("Length: " + r2.getLength()); // 5.0
System.out.println("Width: " + r2.getWidth()); // 3.0
System.out.println("Perimeter: " + r2.getPerimeter()); // 16.0
System.out.println("Area: " + r2.getArea()); // 15.0
r2.setLength(7.0);
r2.setWidth(4.0);
System.out.println("Length: " + r2.getLength()); // 7.0
System.out.println("Width: " + r2.getWidth()); // 4.0
System.out.println("Perimeter: " + r2.getPerimeter()); // 22.0
System.out.println("Area: " + r2.getArea()); // 28.0
}
```
输出结果应该为:
```
Length: 0.0
Width: 0.0
Perimeter: 0.0
Area: 0.0
Length: 5.0
Width: 3.0
Perimeter: 16.0
Area: 15.0
Length: 7.0
Width: 4.0
Perimeter: 22.0
Area: 28.0
```
阅读全文