java创建一个图形类,该类里有求体积的方法getV(),利用方法重载求圆柱体、长方体及圆锥体的体积,并通过主类实现输出这3个不同类型图形的体积。
时间: 2024-05-05 15:17:04 浏览: 96
以下是Java代码实现:
```
public class Graph {
// 求圆柱体体积
public double getV(double r, double h) {
return Math.PI * r * r * h;
}
// 求长方体体积
public double getV(double l, double w, double h) {
return l * w * h;
}
// 求圆锥体体积
public double getV(double r, double h, double k) {
return Math.PI * r * r * h * k / 3;
}
}
public class Main {
public static void main(String[] args) {
Graph graph = new Graph();
double r = 5.0, h1 = 10.0, l = 4.0, w = 6.0, h2 = 8.0, k = 3.0;
System.out.println("圆柱体体积:" + graph.getV(r, h1));
System.out.println("长方体体积:" + graph.getV(l, w, h2));
System.out.println("圆锥体体积:" + graph.getV(r, h1, k));
}
}
```
输出结果:
```
圆柱体体积:785.3981633974483
长方体体积:192.0
圆锥体体积:78.53981633974483
```
阅读全文