用Java定义一个抽象类Shape,它包含一个抽象方法getArea(),从Shape类派生出Rectangle和Circle类,这两个类都用getArea()方法计算对象的面积。编写应用程序使用Rectange和Circle类。
时间: 2023-11-28 20:48:50 浏览: 34
下面是 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;
}
}
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(3, 4);
System.out.println("Rectangle area: " + rectangle.getArea());
Shape circle = new Circle(5);
System.out.println("Circle area: " + circle.getArea());
}
}
```
在上述代码中,我们首先定义了抽象类 `Shape`,其中包含一个抽象方法 `getArea()`。然后我们定义了两个类 `Rectangle` 和 `Circle`,它们都继承自 `Shape` 类,并实现了 `getArea()` 方法来计算面积。最后在主函数中,我们创建了 `Rectangle` 和 `Circle` 的对象,并调用它们的 `getArea()` 方法来计算面积并输出。