java编写一个长方体类
时间: 2024-04-29 14:24:49 浏览: 85
好的,可以为您讲解如何编写一个Java长方体类。一个长方体类需要包含长度、宽度和高度等属性,以及计算体积和表面积的方法。以下是一个可能的实现:
```
public class Cuboid {
private double length;
private double width;
private double height;
public Cuboid(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * (length * width + length * height + width * height);
}
}
```
您可以在Java程序中创建一个Cuboid对象,并调用getVolume()和getSurfaceArea()方法来获取长方体的体积和表面积。如下所示:
```
Cuboid cuboid = new Cuboid(4.0, 5.0, 6.0);
double volume = cuboid.getVolume(); // 120.0
double surfaceArea = cuboid.getSurfaceArea(); // 148.0
```
阅读全文