JAVA——面积计算(final和抽象类)

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);
    }
}

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值