java代码用多态性实现求各种图形的面积之和。
时间: 2024-03-03 09:48:55 浏览: 20
下面是一个使用多态性实现求各种图形面积之和的Java代码示例:
```java
abstract class Shape {
public abstract double getArea();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
public class AreaCalculator {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Rectangle(5, 10);
shapes[1] = new Circle(3);
shapes[2] = new Triangle(4, 6);
double totalArea = 0;
for (int i = 0; i < shapes.length; i++) {
totalArea += shapes[i].getArea();
}
System.out.println("Total area: " + totalArea);
}
}
```
在这个示例中,我们定义了一个抽象类 `Shape`,它有一个抽象的方法 `getArea()`,用于计算图形的面积。然后我们定义了三个具体的子类 `Rectangle`、`Circle` 和 `Triangle`,它们分别重写了 `getArea()` 方法,用于计算自己的面积。
在 `AreaCalculator` 类中,我们创建了一个 `Shape` 类型的数组 `shapes`,并将三种不同的图形对象分别赋值给它的元素。然后我们遍历这个数组,对每个元素调用 `getArea()` 方法,将它们的面积累加到变量 `totalArea` 中。最后输出 `totalArea` 的值,即为三种图形的面积之和。
由于使用了多态性,我们可以将不同的图形对象放到同一个数组中进行处理,这样就可以方便地计算它们的面积之和。