利用接口多态和抽象类求圆 三角形 矩形 面积
时间: 2023-07-04 18:10:18 浏览: 63
可以定义一个抽象类 `Shape`,其中包含一个抽象方法 `getArea()`,用于计算形状的面积。然后分别创建三个子类 `Circle`、`Triangle` 和 `Rectangle` 并实现 `getArea()` 方法,以具体计算各自形状的面积。
以下是示例代码:
```
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
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;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
class Rectangle extends Shape {
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;
}
}
```
然后在主函数中,我们可以通过多态的方式调用各个形状的 `getArea()` 方法,例如:
```
public static void main(String[] args) {
Shape[] shapes = new Shape[] {
new Circle(5),
new Triangle(10, 3),
new Rectangle(4, 6)
};
for (Shape shape : shapes) {
System.out.println("Area of " + shape.getClass().getSimpleName() + " = " + shape.getArea());
}
}
```
输出:
```
Area of Circle = 78.53981633974483
Area of Triangle = 15.0
Area of Rectangle = 24.0
```