请用接口实现以下UML图 ,Java程序:使用匿名类实现,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 16:08:22 浏览: 99
Java 实验 用接口实现求三角形,圆形,矩形的面积和周长
5星 · 资源好评率100%
```java
//定义接口Geometry
interface Geometry {
double getArea();
}
//定义三角形类Triangle,实现Geometry接口
class Triangle implements Geometry {
double a, b, c;
Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
//定义圆形类Circle,实现Geometry接口
class Circle implements Geometry {
double r;
Circle(double r) {
this.r = r;
}
public double getArea() {
return Math.PI * r * r;
}
}
//定义矩形类Rectangle,实现Geometry接口
class Rectangle implements Geometry {
double a, b;
Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
public double getArea() {
return a * b;
}
}
//定义柱体类Pillar
class Pillar {
double height;
Geometry bottom;
Pillar(Geometry bottom, double height) {
this.bottom = bottom;
this.height = height;
}
public double getVolume() {
return bottom.getArea() * height;
}
}
public class Main {
public static void main(String[] args) {
//创建三角形、圆形、矩形对象
Geometry triangle = new Triangle(3, 4, 5);
Geometry circle = new Circle(2);
Geometry rectangle = new Rectangle(3, 4);
//创建三个柱体对象
Pillar pillar1 = new Pillar(triangle, 6);
Pillar pillar2 = new Pillar(circle, 6);
Pillar pillar3 = new Pillar(rectangle, 6);
//输出三个柱体的体积
System.out.println("三角形底的柱体体积为:" + pillar1.getVolume());
System.out.println("圆形底的柱体体积为:" + pillar2.getVolume());
System.out.println("矩形底的柱体体积为:" + pillar3.getVolume());
}
}
```
--相关问题--:
1. 什么是接口?接口和抽象类有什么
阅读全文