按照下面的类图设计并实现三个类: GeometricObject + getArea() : double Rectangle + Rectangle(double, double) + getArea() : double Circle + Circle(double) + getArea() : double 注意:父类GeometricObject类是抽象类,可以根据需要为子类Rectangle类和Circle类提供相应的属性。 按照下面的类图设计并实现柱体类(Pillar): Pillar + Pillar(GeometricObject, double) + getVolume() : double + toString() : String - bottom : GeometricObject - height : double 其中:getVolume()方法用于计算柱体的体积,toString()方法用于返回一个字符串,根据底面图形的类型返回“这是一个圆柱体”或“这是一个长方体”。 编写一个测试类(PillarDemo),在main方法中按照下列步骤进行测试: 1) 创建一个半径为3.5的圆对象,输出其面积; 2) 以上面的圆对象为底创建一个高为2.3的柱体对象,输出这个对象的字符串表示形式和它的体积; 3) 创建一个长为4.8,宽为3.2,高为7.4的柱体对象,输出这个对象的字符串表示形式和它的体积。
时间: 2024-03-24 21:36:15 浏览: 67
以下为Java代码实现:
GeometricObject.java
```
public abstract class GeometricObject {
public abstract double getArea();
}
```
Rectangle.java
```
public class Rectangle extends GeometricObject {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
```
Circle.java
```
public class Circle extends GeometricObject {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
```
Pillar.java
```
public class Pillar {
private GeometricObject bottom;
private double height;
public Pillar(GeometricObject bottom, double height) {
this.bottom = bottom;
this.height = height;
}
public double getVolume() {
return bottom.getArea() * height;
}
@Override
public String toString() {
if (bottom instanceof Circle) {
return "这是一个圆柱体";
} else if (bottom instanceof Rectangle) {
return "这是一个长方体";
} else {
return "";
}
}
}
```
PillarDemo.java
```
public class PillarDemo {
public static void main(String[] args) {
Circle circle = new Circle(3.5);
System.out.println("圆的面积为:" + circle.getArea());
Pillar pillar1 = new Pillar(circle, 2.3);
System.out.println(pillar1.toString() + ",体积为:" + pillar1.getVolume());
Rectangle rectangle = new Rectangle(4.8, 3.2);
Pillar pillar2 = new Pillar(rectangle, 7.4);
System.out.println(pillar2.toString() + ",体积为:" + pillar2.getVolume());
}
}
```
输出结果:
```
圆的面积为:38.48451000647496
这是一个圆柱体,体积为:263.92151046679473
这是一个长方体,体积为:113.27999999999999
```
阅读全文