a.

public interface Shape {
    double getArea();
    double getPerimeter();
}

public class Circle implements Shape {
    private double radius;

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

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }

    @Override
    public double getPerimeter() {
        return 2 * Math.PI * radius;
    }

    public double getDiameter() {
        return 2 * radius;
    }
}

public class TestCircle {
    public static void main(String[] args) {
        Circle circle = new Circle(5);
        System.out.println("圆的面积为:" + circle.getArea());
        System.out.println("圆的周长为:" + circle.getPerimeter());
    }
}

b.

public class Rectangle implements Shape {
    private double length;
    private double width;

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

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    @Override
    public double getArea() {
        return length * width;
    }

    @Override
    public double getPerimeter() {
        return 2 * (length + width);
    }

    public boolean isSquare() {
        return length == width;
    }
}

public class TestRectangle {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(3, 4);
        System.out.println("矩形的面积为:" + rectangle.getArea());
        System.out.println("矩形的周长为:" + rectangle.getPerimeter());
    }
}
三如图所示设计一个形状类接口Shape表示图形。其中getArea方法求面积getPerimeter求周长。a 编写Shape的子类圆类Circle。覆盖Shape的三个方法并增加各自的方法。编写用户程序TestCircle创建一个圆求圆的面积和周长并打印出来。b 编写Shape的子类矩形类Rectangle。覆盖Shape的2个方法并增加各自的方法。编写用户程序TestRectangle创建一个

原文地址: https://www.cveoy.top/t/topic/7Re 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录