7-14打卡

Java抽象类

abstract class Shape {
    abstract double calculateArea(); // 抽象方法
}

class Rectangle extends Shape {
    private double length;
    private double width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    double calculateArea() {
        return length * width;
    }
}

class Circle extends Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    double calculateArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape rectangle = new Rectangle(5, 3);
        double rectangleArea = rectangle.calculateArea();
        System.out.println("Rectangle area: " + rectangleArea);

        Shape circle = new Circle(2.5);
        double circleArea = circle.calculateArea();
        System.out.println("Circle area: " + circleArea);
    }
}

posted @ 2023-07-14 19:32  aallofitisst  阅读(9)  评论(0)    收藏  举报