写一个Copyable接口,计算长宽高分别为2,5,4的长方体,底面半径为4,高为5的圆柱体,半径为5的球体的体积
时间: 2024-03-05 11:49:29 浏览: 69
好的,下面是一个可能的实现:
```java
public interface Copyable {
double getVolume();
Copyable copy();
}
public class Cuboid implements Copyable {
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;
}
@Override
public double getVolume() {
return length * width * height;
}
@Override
public Copyable copy() {
return new Cuboid(length, width, height);
}
}
public class Cylinder implements Copyable {
private double radius;
private double height;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
public double getVolume() {
return Math.PI * radius * radius * height;
}
@Override
public Copyable copy() {
return new Cylinder(radius, height);
}
}
public class Sphere implements Copyable {
private double radius;
public Sphere(double radius) {
this.radius = radius;
}
@Override
public double getVolume() {
return 4.0 / 3.0 * Math.PI * Math.pow(radius, 3);
}
@Override
public Copyable copy() {
return new Sphere(radius);
}
}
public class Main {
public static void main(String[] args) {
Cuboid cuboid = new Cuboid(2, 5, 4);
System.out.println("长方体的体积为:" + cuboid.getVolume());
Cylinder cylinder = new Cylinder(4, 5);
System.out.println("圆柱体的体积为:" + cylinder.getVolume());
Sphere sphere = new Sphere(5);
System.out.println("球体的体积为:" + sphere.getVolume());
}
}
```
这里定义了一个 `Copyable` 接口,和三个实现了该接口的类,分别表示长方体、圆柱体和球体。接着在 `Main` 类的 `main` 方法中创建了这三个对象,并调用了它们的 `getVolume` 方法来计算体积。注意,这里的参数分别对应于题目中所给出的长宽高和半径高。
阅读全文