定义一个抽象类Shape,它包含一个抽象方法getArea(),从Shape类派生出Rectangle和Circle类,这两个类都用getArea()方法计算对象的面积。编写应用程序使用Rectang...
时间: 2023-11-28 14:49:03 浏览: 208
下面是一个可能的实现:
```
// Shape 抽象类
abstract class Shape {
public abstract double getArea();
}
// Rectangle 类
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
}
// Circle 类
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
// 应用程序
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[2];
shapes[0] = new Rectangle(3, 4);
shapes[1] = new Circle(2);
for (Shape s : shapes) {
System.out.println("Area = " + s.getArea());
}
}
}
```
这个实现中,`Shape` 是一个抽象类,它包含一个抽象方法 `getArea()`,用于计算形状的面积。`Rectangle` 和 `Circle` 都是 `Shape` 的子类,并实现了 `getArea()` 方法。在应用程序中,我们创建了一个 `Shape` 数组,并分别用 `Rectangle` 和 `Circle` 对象填充它,然后使用 `getArea()` 方法计算每个形状的面积并打印结果。