第十三章第六题(ComparableCircle类)(ComparableCircle class)

第十三章第六题(ComparableCircle类)(ComparableCircle class)

  • *13.6(ComparableCircle类)创建名为ComparableCircle的类,他继承自Circle 类,并实现Comparable接口。画出UML图并实现compareTo方法,使其根据面积比较两个圆。编写一个测试程序求出两个ComparableCircle实例对象的较大者,以及一个圆和一个矩形的较大者。
    *13.6(ComparableCircle class)Create a class named comparablecircle, which inherits from the circle class and implements the comparable interface. Draw the UML diagram and implement the CompareTo method to compare two circles according to the area. Write a test program to find the larger of two comparablecircle instance objects, and the larger of a circle and a rectangle.
  • 参考代码:
package chapter13;

public class Code_06 {
    public static void main(String [] args) {
        ComparableCircle circle1 = new ComparableCircle(3);
        ComparableCircle circle2 = new ComparableCircle(4);
        if (circle1.compareTo(circle2) == 1)
            System.out.println("circle1 is bigger");
        else if (circle1.compareTo(circle2) == -1)
            System.out.println("circle2 is bigger");
        else if (circle1.compareTo(circle2) == 0)
            System.out.println("circle1 is the same as circle2");
        ComparableRectangle rectangle = new ComparableRectangle(2,4);
        System.out.println(circle1.getArea() > rectangle.getArea() ? "circle1 bigger than rectangle" : "rectangle is bigger than circle1");
    }
}
class ComparableCircle extends Circle implements Comparable<ComparableCircle> {
    public ComparableCircle() {
    }

    public ComparableCircle(double radius) {
        super(radius);
    }

    public Object max(ComparableCircle o1, ComparableCircle o2) {
        if (o1.compareTo(o2) > 0)
            return o1;
        else
            return o2;
    }

    public int compareTo(ComparableCircle o) {
        if (super.getArea() > o.getArea())
            return 1;
        else if (super.getArea() < o.getArea())
            return -1;
        else
            return 0;
    }
}

  • 结果显示:
circle2 is bigger
circle1 bigger than rectangle

Process finished with exit code 0

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值