用java编写一个底面积的抽象类ThreeDimen并将圆球、圆柱、圆锥、长方体、正方体,根据传递的参数计算三维图形的体积。
时间: 2023-06-02 15:03:57 浏览: 92
好的,这是一个技术问题,我可以回答。以下是代码示例:
```
public abstract class ThreeDimen {
public abstract double getArea();
public abstract double getVolume(double... args);
}
class Sphere extends ThreeDimen {
private double radius;
Sphere(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return 4 * Math.PI * radius * radius;
}
@Override
public double getVolume(double... args) {
return 4 / 3.0 * Math.PI * radius * radius * radius;
}
}
class Cylinder extends ThreeDimen {
private double radius;
private double height;
Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
public double getArea() {
return 2 * Math.PI * radius * height + 2 * Math.PI * radius * radius;
}
@Override
public double getVolume(double... args) {
return Math.PI * radius * radius * height;
}
}
class Cone extends ThreeDimen {
private double radius;
private double height;
Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
public double getArea() {
double slantHeight = Math.sqrt(radius * radius + height * height);
return Math.PI * radius * slantHeight + Math.PI * radius * radius;
}
@Override
public double getVolume(double... args) {
return 1 / 3.0 * Math.PI * radius * radius * height;
}
}
class RectangularSolid extends ThreeDimen {
private double length;
private double width;
private double height;
RectangularSolid(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return 2 * (length * width + length * height + width * height);
}
@Override
public double getVolume(double... args) {
return length * width * height;
}
}
class Cube extends ThreeDimen {
private double side;
Cube(double side) {
this.side = side;
}
@Override
public double getArea() {
return 6 * side * side;
}
@Override
public double getVolume(double... args) {
return side * side * side;
}
}
```
我们可以创建各种不同的三维图形对象,然后调用它们的getVolume方法来计算它们的体积,比如这样:
```
public static void main(String[] args) {
ThreeDimen sphere = new Sphere(5);
ThreeDimen cylinder = new Cylinder(3, 10);
ThreeDimen cone = new Cone(4, 8);
ThreeDimen rectSolid = new RectangularSolid(5, 6, 7);
ThreeDimen cube = new Cube(4);
double sphereVolume = sphere.getVolume();
double cylinderVolume = cylinder.getVolume();
double coneVolume = cone.getVolume();
double rectSolidVolume = rectSolid.getVolume();
double cubeVolume = cube.getVolume();
System.out.println("Sphere volume: " + sphereVolume);
System.out.println("Cylinder volume: " + cylinderVolume);
System.out.println("Cone volume: " + coneVolume);
System.out.println("Rectangular solid volume: " + rectSolidVolume);
System.out.println("Cube volume: " + cubeVolume);
}
```
这将输出每个图形的体积。希望这可以帮助你解决问题!
阅读全文