Java定义一个计算矩形面积,立方体和球体体积的类。该类完成计算的方法用静态方法实现
时间: 2023-12-03 08:45:07 浏览: 84
可以定义一个名为`Geometry`的类,其中包含三个静态方法`rectangleArea()`、`cubeVolume()`和`sphereVolume()`,分别用于计算矩形面积、立方体体积和球体体积。具体实现如下:
```java
public class Geometry {
// 计算矩形面积
public static double rectangleArea(double width, double height) {
return width * height;
}
// 计算立方体体积
public static double cubeVolume(double sideLength) {
return Math.pow(sideLength, 3);
}
// 计算球体体积
public static double sphereVolume(double radius) {
return 4.0 / 3.0 * Math.PI * Math.pow(radius, 3);
}
}
```
使用示例:
```java
double width = 10.0;
double height = 5.0;
double sideLength = 3.0;
double radius = 2.0;
double rectangleArea = Geometry.rectangleArea(width, height);
double cubeVolume = Geometry.cubeVolume(sideLength);
double sphereVolume = Geometry.sphereVolume(radius);
System.out.println("矩形面积:" + rectangleArea);
System.out.println("立方体体积:" + cubeVolume);
System.out.println("球体体积:" + sphereVolume);
```
阅读全文