定义一个MyRectangle类,它不但具有Rectangle类所有的功能,它还具有如下功能: (1)Comparable接口,面积作为比较依据 (2)创建MyRectangle类型的数组,每个元素重写toString方法。假设当前对象的长和高是3和2,那么toString方法返回“width: 3, height:2” (2)重写equals方法。当两个MyRectangle实例的面积相等时,认为两个对象是相等的
时间: 2024-03-23 22:41:11 浏览: 53
好的,以下是MyRectangle类的代码实现:
```java
import java.awt.Rectangle;
public class MyRectangle extends Rectangle implements Comparable<MyRectangle> {
public MyRectangle(int width, int height) {
super(width, height);
}
@Override
public int compareTo(MyRectangle o) {
return Double.compare(this.getWidth() * this.getHeight(), o.getWidth() * o.getHeight());
}
@Override
public String toString() {
return "width: " + this.getWidth() + ", height: " + this.getHeight();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MyRectangle)) {
return false;
}
MyRectangle other = (MyRectangle) obj;
return this.getWidth() * this.getHeight() == other.getWidth() * other.getHeight();
}
}
```
这里的MyRectangle类继承自Java自带的Rectangle类,并实现了Comparable接口,重写了toString和equals方法。
接下来是创建MyRectangle数组并重写toString方法的代码:
```java
public class Main {
public static void main(String[] args) {
MyRectangle[] rectangles = new MyRectangle[3];
rectangles[0] = new MyRectangle(3, 2);
rectangles[1] = new MyRectangle(4, 1);
rectangles[2] = new MyRectangle(2, 5);
for (MyRectangle r : rectangles) {
System.out.println(r.toString());
}
}
}
```
最后是equals方法的使用示例:
```java
public class Main {
public static void main(String[] args) {
MyRectangle r1 = new MyRectangle(3, 2);
MyRectangle r2 = new MyRectangle(2, 3);
MyRectangle r3 = new MyRectangle(5, 1);
System.out.println(r1.equals(r2)); // true
System.out.println(r1.equals(r3)); // false
}
}
```
希望我的回答能够解决你的问题,如果还有什么需要帮助的地方,请随时提出。
阅读全文