设计一个抽象类图形类,在该类中包含有至少两个抽象方法求周长和求面积,分别定义圆形类、长方形类、正方形类来继承图形类,并实现上述两个方法。并创建实例验证。

(1)【抽象类方法】public abstract class Shape {
    public abstract double area();
    public abstract double perimeter();
}
【圆继承方法】public class Circle extends Shape {//圆面积

    private double diameter;

    public double getDiameter() {
        return diameter;
    }

    public void setDiameter(double diameter) {
        this.diameter = diameter;
    }

    @Override
    public double area() {
        return Math.PI * Math.pow(getDiameter() / 2, 2);
    }

    @Override
    public double perimeter() {
        return Math.PI * getDiameter();
    }

}
【矩形继承】public class Rectangle extends Shape {//矩形周长

    private double length;
    private double 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 area() {
        return getLength() * getWidth();
    }

    @Override
    public double perimeter() {
        return 2 * (getWidth() + getWidth());
    }
}

【主类方法实现】public class no1 {
    public static void main(String[] args) {

        Rectangle rec = new Rectangle();
        rec.setLength(10);
        rec.setWidth(5);
        double rec_area = rec.area();
        double rec_perimeter = rec.perimeter();
        System.out.println("矩形的面积:"+rec_area+",周长"+rec_perimeter);

        Circle cir = new Circle();
        cir.setDiameter(10);
        double cir_area = cir.area();
        double cir_perimeter = cir.perimeter();
        System.out.println("圆形的面积:"+cir_area+",周长"+cir_perimeter);
    }

}

 

你可能感兴趣的:(Java)