写一个Copyable接口,计算长方体,圆柱体,球体的体积
时间: 2024-03-05 09:49:16 浏览: 88
好的,下面是一个可能的实现:
```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);
}
}
```
这里定义了一个 `Copyable` 接口,它包括两个方法:`getVolume()` 返回体积,`copy()` 返回一个与当前对象相同的新对象。然后定义了三个实现了 `Copyable` 接口的类,分别表示长方体、圆柱体和球体。每个类都实现了 `getVolume()` 和 `copy()` 方法,通过这些方法可以计算出体积并创建新的对象。
阅读全文