(Java)7-1 jmu-Java-03面向对象基础-04-形状-继承

题目要求

在这里插入图片描述

样例

在这里插入图片描述



import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Shape[] shape = new Shape[n];
        double sumArea=0,sumPerimeter=0;

        for (int i=0;i<n;i++){
            String s = sc.next();
            if (s.equals("rect")){//长方形
                int width = sc.nextInt();
                int length = sc.nextInt();
                shape[i] = new Rectangle(width,length);

            }
            else{
                int radius = sc.nextInt();
                shape[i] = new Circle(radius);

            }
			//累加
            sumArea +=shape[i].getArea();
            sumPerimeter += shape[i].getPerimeter();

        }
        System.out.println(sumPerimeter);
        System.out.println(sumArea);


        System.out.print("[");
        for (int i=0;i<n;i++){
            System.out.print(shape[i].toString());
            if (i!=n-1) System.out.print(", ");

        }
        System.out.println("]");
        for (int i=0;i<n;i++){
        //获得类名和父类名
        System.out.println(shape[i].getClass()+","+shape[i].getClass().getSuperclass());

        }

    }
}

abstract class Shape{
    static double PI = 3.14;

    public abstract double getPerimeter();

    public abstract double getArea();
}

class Rectangle extends Shape{

    int length,width;
    double area,perimeter;

    public Rectangle(int width,int length){
        this.width = width;
        this.length = length;

    }

    @Override
    public double getPerimeter() {
        perimeter = 2*(width+length);
        return perimeter;
    }

    @Override
    public double getArea() {
        area = width*length;
        return area;
    }

    public String toString(){
        return "Rectangle [width="+width+", length="+length+"]";
    }
}

class Circle extends Shape{

    int radius;
    double area,perimeter;


    public Circle (int radius){
        this.radius = radius;

    }

    @Override
    public double getPerimeter() {
        perimeter = PI*2*radius;
        return perimeter;
    }

    @Override
    public double getArea() {
        area = PI*radius*radius;
        return area;
    }

    public String toString(){
        return "Circle [radius="+radius+"]";
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG--ER

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值