1. 创建一个抽象类 `Shape`,它包含一个抽象方法 `area()` 用于计算面积。
2. 创建两个从 `Shape` 继承的具体类:`Circle` 和 `Rectangle`。设置常量PI。
- `Circle` 类有一个属性 `radius`(半径,类型为 `double`),构造函数需要初始化这个属性。实现 `area()` 方法,返回圆的面积(使用公式 `PI * radius * radius`)。
- `Rectangle` 类有两个属性 `width` 和 `height`(宽和高,类型都为 `double`),构造函数需要初始化这两个属性。实现 `area()` 方法,返回矩形的面积(使用公式 `width * height`)。
3. 在 `main` 方法中创建 `Circle` 和 `Rectangle` 的实例,计算并打印出它们的面积。
// 抽象类 Shape
abstract class Shape {
abstract double area();
}
// Circle 类继承自 Shape
class Circle extends Shape {
static final double PI = 3.141592653589793;
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return PI * radius * radius;
}
}
// Rectangle 类继承自 Shape
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
public class Domo_01 {
public static void main(String[] args){
// 创建 Circle 实例并计算面积
Circle circle = new Circle(5.0);
double circleArea = circle.area();
System.out.println("Circle area: " + circleArea);
// 创建 Rectangle 实例并计算面积
Rectangle rectangle = new Rectangle(4.0, 6.0);
double rectangleArea = rectangle.area();
System.out.println("Rectangle area: " + rectangleArea);
}
}