已知,抽象类Germetry(几何图形)有1个抽象方法getArea()(求面积),请设计它的两个子类三角形类Triangle和梯形类Trapezoid。柱体类Pillar有bottom(底)和height(高)以及getVolume()(求体积)功能。UML图如下。编写主类,要求能够输出以三角形为底的柱体体积和以梯形为底的柱体体积。(参考教材5.10完成)
时间: 2024-02-17 14:01:54 浏览: 59
实现抽象类求面积方法
好的,以下是可能的解答。
首先,我们需要定义抽象类Germetry,包含抽象方法getArea():
```java
abstract class Germetry {
public abstract double getArea();
}
```
然后,我们可以定义两个子类Triangle和Trapezoid,它们分别继承自Germetry并实现getArea()方法:
```java
class Triangle extends Germetry {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
class Trapezoid extends Germetry {
private double top;
private double bottom;
private double height;
public Trapezoid(double top, double bottom, double height) {
this.top = top;
this.bottom = bottom;
this.height = height;
}
@Override
public double getArea() {
return (top + bottom) * height / 2;
}
}
```
接下来,我们可以定义柱体类Pillar,它包含bottom和height属性以及getVolume()方法:
```java
class Pillar {
private Germetry bottom;
private double height;
public Pillar(Germetry bottom, double height) {
this.bottom = bottom;
this.height = height;
}
public double getVolume() {
return bottom.getArea() * height;
}
}
```
最后,我们可以编写主类,输出以三角形为底的柱体体积和以梯形为底的柱体体积:
```java
public class Main {
public static void main(String[] args) {
Germetry triangle = new Triangle(3, 4);
Germetry trapezoid = new Trapezoid(2, 4, 3);
Pillar pillar1 = new Pillar(triangle, 5);
Pillar pillar2 = new Pillar(trapezoid, 5);
System.out.println("Triangle-based Pillar Volume: " + pillar1.getVolume());
System.out.println("Trapezoid-based Pillar Volume: " + pillar2.getVolume());
}
}
```
输出结果应该是:
```
Triangle-based Pillar Volume: 30.0
Trapezoid-based Pillar Volume: 35.0
```
阅读全文