定义一个MyRectangle类,它不但具有Rectangle类所有的功能,它还具有如下功能: (1)重写toString方法。假设当前对象的长和高是3和2,那么toString方法返回“width: 3, height:2”(2)重写equals方法。当两个MyRectangle实例的面积相等时,认为两个对象是相等的
时间: 2024-03-23 22:36:18 浏览: 18
好的,下面是实现MyRectangle类的代码示例:
```java
import java.awt.Rectangle;
public class MyRectangle extends Rectangle {
public MyRectangle(int width, int height) {
super(width, height);
}
@Override
public String toString() {
return "width: " + super.width + ", height: " + super.height;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MyRectangle)) {
return false;
}
MyRectangle other = (MyRectangle) obj;
return this.width * this.height == other.width * other.height;
}
}
```
在上面的代码中,我们继承了Java自带的Rectangle类,并重写了它的toString和equals方法。toString方法返回“width: 宽度, height: 高度”,equals方法判断两个MyRectangle对象的面积是否相等,如果相等则认为两个对象相等。
使用示例:
```java
MyRectangle r1 = new MyRectangle(3, 2);
MyRectangle r2 = new MyRectangle(4, 2);
System.out.println(r1.toString()); // 输出 "width: 3, height: 2"
System.out.println(r1.equals(r2)); // 输出 true,因为r1和r2的面积都是6
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)