封装继承和多态

设计一个形状类(接口)Shape,方法:求周长和求面积
形状类(接口)的子类(实现类):
    Rect(矩形)
    Circle(圆形)

/*
 * 设计一个形状类(接口)Shape,方法:求周长和求面积
 * */
public interface Shape {
    double perimeter();//周长
    double area();//面积
}
public class Rect implements Shape {
    private double height;//高
    private double wide;//宽

    @Override
    public double area(){
        return wide * height;
    }
    @Override
    public double perimeter(){
        return 2*(wide + height);
    }

    public double getHeight() {
        return height;
    }

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

    public double getWide() {
        return wide;
    }

    public void setWide(double wide) {
        this.wide = wide;
    }

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

    public Rect(double wide) {
        this.wide = wide;
    }
}
public class Circle implements Shape{
        private final double a=3.14;//圆周率
        private double radius;//半径
        @Override
        public double perimeter(){
            return 2*a*radius;
        }
        @Override
        public double area(){
            return a*radius*radius;
        }

        public double getA() {
            return a;
        }

        public double getRadius() {
            return radius;
        }

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

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

        public Circle() {
        }
    }

Rect类的子类:
    Square(正方形)

public class Square extends Rect{
    @Override
    public double area(){
        return getWide() * getWide();
    }
    @Override
    public double perimeter(){
        return 4*getWide();
    }

    public Square(double height, double wide) {
        super(height, wide);
    }

    public Square(double wide) {
        super(wide);
    }
}
public class Test {
        public static void main(String[] args) {
            Shape[] shapes = new Shape[3];
            shapes[0]=new Circle(2);
            shapes[1]=new Rect(3,8);
            shapes[2]=new Square(7);
            System.out.println("圆,矩形,正方体");
            for (int i = 0; i < shapes.length; i++) {
                System.out.println(""+"面积为"+shapes[i].area()+"周长为"+shapes[i].perimeter());
            }
        }
    }

运行结果

圆,矩形,正方体
面积为12.56周长为12.56
面积为24.0周长为22.0
面积为49.0周长为28.0

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值