改写第1题中的Circle类,它继承自GeometricObject类并实 现Comparable接口。重写Object类中的equals方法。当两 个Circle对象半径相等时,则这两个Circle对象是相同的。 GeometricObject类的定义应该这样开始: abstract class GeometricObject { 也就是说,GeometricObject类的class前面不要有public。 Circle类的定义应该这样开始: class Circle extends GeometricObject implements Comparable<Circle> {
时间: 2023-06-18 12:07:50 浏览: 152
以下是改写后的Circle类的代码:
```java
abstract class GeometricObject {
private String color;
private boolean filled;
public GeometricObject() {
this.color = "white";
this.filled = false;
}
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
class Circle extends GeometricObject implements Comparable<Circle> {
private double radius;
public Circle() {
super();
this.radius = 1.0;
}
public Circle(double radius) {
super();
this.radius = radius;
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
@Override
public boolean equals(Object o) {
if (o instanceof Circle) {
Circle c = (Circle) o;
return Double.compare(radius, c.radius) == 0;
}
return false;
}
@Override
public int compareTo(Circle c) {
return Double.compare(radius, c.radius);
}
}
```
其中,重写的equals方法会判断输入的对象是否是Circle类型,然后比较两个Circle对象的半径是否相等。如果相等,则返回true,否则返回false。重写的compareTo方法是实现Comparable接口的方法,比较两个Circle对象的半径大小。如果当前对象的半径小于输入对象的半径,返回负数;如果当前对象的半径等于输入对象的半径,返回0;如果当前对象的半径大于输入对象的半径,返回正数。
阅读全文