计算形状周长面积

接口

public interface Shape {

// 求⾯积⽅法

    double getArea();

// 求周长⽅法

    double getPerimeter();

}


Rect(矩形)

public class Rect implements Shape { private double width;// 宽
        private double 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;
        }

        // ⼀个参数构造,给⼦类正⽅形⽤
        public Rect(double width){
            this.width = width;
        }

        //两个参数的构造,⾃⼰⽤
        public Rect(double width,double height){ this.height = height;
            this.width = width;
        }


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

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


Circle(圆形)

public class Circle implements Shape{
    private final double PI =3.14;//圆周率
    private double r;//半径
    public double getR(){
        return r;
    }

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

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

    @Override
    public double getArea(){
    // TODO Auto-generated method stub
        return PI * r * r;
    }

    @Override
    public double getPerimeter(){
    // TODO Auto-generated method stub
        return PI * r *2;
    }
}

Square(正方形)

public class Square extends Rect{
    public Square(double width){
        super(width);
    }
    @Override
    public double getArea(){
    // TODO Auto-generated method stub
     return getWidth()*getWidth();
    }

    @Override
    public double getPerimeter(){
    // TODO Auto-generated method stub
      return 4*getWidth();
    }

}

Text(测试类)

public class Test {
    public static void main(String[] args){
        Shape[] shape =new Shape[3];
        shape[0]=new Circle(3);
        System.out.println("========圆形周长和⾯积========");
        System.out.println(String.format("%.2f", shape[0].getArea())); System.out.println(shape[0].getPerimeter());
        shape[1]=new Rect(5,8);
        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());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值