用Java语音写一个计算长方体,圆柱体,球体的程序,运用Copyable接口
时间: 2024-03-05 12:49:07 浏览: 186
好的,下面是用 Java 语言实现计算长方体、圆柱体和球体体积的代码,并实现 Copyable 接口:
首先是 Copyable 接口的定义:
```java
public interface Copyable {
public Object copy();
}
```
然后是长方体、圆柱体和球体的实现:
```java
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;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return length * width * height;
}
@Override
public Object 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;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return Math.PI * radius * radius * height;
}
@Override
public Object copy() {
return new Cylinder(radius, height);
}
}
public class Sphere implements Copyable {
private double radius;
public Sphere(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getVolume() {
return 4.0 / 3.0 * Math.PI * radius * radius * radius;
}
@Override
public Object copy() {
return new Sphere(radius);
}
}
```
最后,我们可以使用这些类来计算体积,以及复制对象:
```java
public class Main {
public static void main(String[] args) {
Cuboid cuboid = new Cuboid(3, 4, 5);
Cylinder cylinder = new Cylinder(2, 5);
Sphere sphere = new Sphere(3);
System.out.println("Cuboid volume: " + cuboid.getVolume());
System.out.println("Cylinder volume: " + cylinder.getVolume());
System.out.println("Sphere volume: " + sphere.getVolume());
// 复制对象
Cuboid cuboidCopy = (Cuboid) cuboid.copy();
System.out.println("Cuboid copy volume: " + cuboidCopy.getVolume());
}
}
```
希望这段代码能够帮到你,如果你有任何问题或者需要进一步的帮助,请随时向我提问。
阅读全文