JAVA语言计算周长和面积的方法

​先创建接口类

package Zuoye.Dog.Zhoumj;

public interface Shape {//接口
    double getArea();
    double getPerimeter();
}

圆类,声明圆的属性圆周率和圆的半径,进行公式计算

package Zuoye.Dog.Zhoumj;

public class Circle implements Shape{
//圆形类
    private final double PI=3.14;//圆周率
    private double r;//半径

    @Override//面积
    public double getArea() {
        return PI* r*r;
    }

    @Override
    public double getPerimeter() {//周长
        return PI*r*2;
    }

    //无参构造重写
    public Circle(double r) {
        this.r=r;
    }

    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }
}

矩形类,声明矩形的属性长和宽,进行公式计算

package Zuoye.Dog.Zhoumj;

public class Rect implements Shape{
    //矩形类
    private double width;//宽
    private double height;//高

    public Rect(double width) {
        this.width = width;
    }

    public Rect(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double getArea() {//面积
        return width*height;
    }

    @Override
    public double getPerimeter() {//周长
        return 2*(width+height);
    }

    public double getWidth() {
        return width;
    }

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

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }
}

正方类,声明正方形的属性长和宽,进行公式计算

package Zuoye.Dog.Zhoumj;

public class Square extends Rect{
    //正方形的类,继承矩形

    public Square(double width) {
        super(width);
    }

    @Override
    public double getArea(){
        return getWidth()*getHeight();
    }
    @Override
    public double getPerimeter(){
        return 4*getWidth();
    }
}

测试类,输入声明圆,矩形,正方形的数据进行计算

package Zuoye.Dog.Zhoumj;

public class Test {
    //测试类
    public static void main(String[] args) {
        Shape[] shape = new Shape[3];
        shape[0] = new Circle(4);//shape[0]编号

        System.out.println("---圆的周长和面积---");
        System.out.println(String.format("%2f",shape[0].getArea()));
        System.out.println(shape[0].getPerimeter());

        shape[1] = new Rect(4,6);
        System.out.println("---矩形周长和面积---");
        System.out.println(shape[1].getArea());
        System.out.println(shape[1].getPerimeter());

        shape[2] = new Square(5);
        System.out.println("---正方形的周长和面积---");
        System.out.println(shape[2].getArea());
        System.out.println(shape[2].getPerimeter());
    }
}

你可能感兴趣的:(java,大数据,算法)