2020-12-06

以Shape抽象类为父类,派生出子类Cicle和Rentangle

/*定义抽象类Shape*/
abstract class Shape{
    protected String name;//声明被保护的变量
    /*构造方法*/
    public Shape(String n){
        name=n;
        System.out.println("名称:"+name);
    }
    abstract public double getArea();
    abstract public double getLength();//声明getArea()和getLength()方法
}
class Circle extends Shape{ //Cicrle子类
    private final double PI = 3.14;
    private double radius;
    public Circle(String shapeName,double r){//构造方法
        super(shapeName);
        radius=r;
    }
    public double getArea(){
        return PI*radius*radius;
    }
    public double getLength(){
        return 2*PI*radius;
    }//实现抽象类中的getArea()和getLength()方法
}
/*Rectangle子类*/
class Rectangle extends Shape{
    private double width;
    private double height;
    public Rectangle(String shapeName,double width,double height){
        super(shapeName);
        this.width=width;
        this.height=height;
    }
    public double getArea(){
        return width*height;
    }
    public double getLength(){
        return 2*(width+height);
    }//实现抽象类中的getArea()和getLength()方法
}
public class abstractapplication {

    public static void main(String[] args) {
        Shape circle =new Circle("圆",10.2);
        System.out.print("圆的面积为"+circle.getArea());
        System.out.println("圆的周长为"+circle.getLength());
        Shape tangle = new Rectangle("矩形",6.5,10.5);
        System.out.print("矩形的面积为"+tangle.getArea());
        System.out.print("矩形的周长为"+tangle.getLength());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值