JAVA编程实现:创建一个图形类,该类里有求体积的方法getV()
时间: 2024-06-02 11:13:56 浏览: 87
JAVA图形编程
3星 · 编辑精心推荐
public class Graph {
public double getV() {
return 0;
}
}
// 各种图形的子类,重写getV()方法
public class Cube extends Graph {
private double a;
public Cube(double a) {
this.a = a;
}
@Override
public double getV() {
return a * a * a;
}
}
public class Sphere extends Graph {
private double r;
public Sphere(double r) {
this.r = r;
}
@Override
public double getV() {
return 4.0 / 3.0 * Math.PI * r * r * r;
}
}
public class Cone extends Graph {
private double r;
private double h;
public Cone(double r, double h) {
this.r = r;
this.h = h;
}
@Override
public double getV() {
return 1.0 / 3.0 * Math.PI * r * r * h;
}
}
// 测试用例
public class Main {
public static void main(String[] args) {
Graph cube = new Cube(3);
Graph sphere = new Sphere(4);
Graph cone = new Cone(2, 5);
System.out.println("Cube volume: " + cube.getV());
System.out.println("Sphere volume: " + sphere.getV());
System.out.println("Cone volume: " + cone.getV());
}
}
阅读全文