java定义矩形类rectangle并计算矩形的面积及周长
时间: 2024-05-12 10:20:48 浏览: 120
```java
public class Rectangle {
private double length; // 矩形的长
private double width; // 矩形的宽
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 getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
```
使用示例:
```java
Rectangle rect = new Rectangle(5.0, 4.0);
System.out.println("矩形的面积为:" + rect.getArea()); // 输出:矩形的面积为:20.0
System.out.println("矩形的周长为:" + rect.getPerimeter()); // 输出:矩形的周长为:18.0
```
阅读全文