设计一个Circle类,该类有属性radius,表示圆的半径,其默认值为1;getArea()返回该圆的面积。 创建一个名为ComparableCircle的类,它继承自Circle类,并实现Comparable接口,在类中实现compareTo方法,使其根据面积比较两个圆。 编写测试程序求出两个ComparableCircle实例对象的较大者。程序输出如下信息: Cirlce: radius = 7.0 Area: 153.93804002589985 Cirlce: radius = 5.0 Area: 78.53981633974483 c1较大
时间: 2024-02-28 18:56:15 浏览: 181
ComparableCircle类
好的,以下是可供参考的代码实现:
```java
class Circle {
protected double radius; // 圆的半径
public Circle() {
this.radius = 1.0; // 默认半径为1
}
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius; // 计算圆的面积
}
}
class ComparableCircle extends Circle implements Comparable<ComparableCircle> {
public ComparableCircle() {
super();
}
public ComparableCircle(double radius) {
super(radius);
}
@Override
public int compareTo(ComparableCircle o) {
if (this.getArea() > o.getArea()) {
return 1;
} else if (this.getArea() < o.getArea()) {
return -1;
} else {
return 0;
}
}
}
public class Test {
public static void main(String[] args) {
ComparableCircle c1 = new ComparableCircle(7.0);
ComparableCircle c2 = new ComparableCircle(5.0);
System.out.println("Circle: radius = " + c1.radius + " Area: " + c1.getArea());
System.out.println("Circle: radius = " + c2.radius + " Area: " + c2.getArea());
if (c1.compareTo(c2) > 0) {
System.out.println("c1较大");
} else if (c1.compareTo(c2) < 0) {
System.out.println("c2较大");
} else {
System.out.println("c1和c2一样大");
}
}
}
```
输出结果:
```
Circle: radius = 7.0 Area: 153.93804002589985
Circle: radius = 5.0 Area: 78.53981633974483
c1较大
```
阅读全文