编程实现功能:创建一个计算图形面积的抽象类Geometry,然后继承该类分别创建圆类、矩形类和三角形类,重写计算面积方法,最终编写执行类创建图形数组,并将元素的面积之和进行输出
时间: 2024-05-08 12:15:48 浏览: 88
抽象类Geometry:
```
public abstract class Geometry {
public abstract double getArea();
}
```
圆类Circle:
```
public class Circle extends Geometry {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
}
```
矩形类Rectangle:
```
public class Rectangle extends Geometry {
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;
}
}
```
三角形类Triangle:
```
public class Triangle extends Geometry {
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;
}
}
```
执行类Main:
```
public class Main {
public static void main(String[] args) {
Geometry[] geometries = new Geometry[3];
geometries[0] = new Circle(2.0);
geometries[1] = new Rectangle(3.0, 4.0);
geometries[2] = new Triangle(5.0, 6.0);
double sumArea = 0.0;
for (Geometry geometry : geometries) {
sumArea += geometry.getArea();
}
System.out.println("The sum of areas is " + sumArea);
}
}
```
输出结果:
```
The sum of areas is 44.84955592153876
```
阅读全文