定义两个类,父类GeometricObject代表几何形状,子类Circle代表圆形写一个测试类,创建两个Circle对象,判断其颜色是否相等;利用equals方法判断其半径是否相等;利用toString()方法输出其半径。
时间: 2024-04-29 13:22:27 浏览: 107
下面是代码实现:
```java
class GeometricObject {
protected String color;
public GeometricObject(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
class Circle extends GeometricObject {
private double radius;
public Circle(double radius, String color) {
super(color);
this.radius = radius;
}
public double getRadius() {
return radius;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Circle) {
Circle circle = (Circle) obj;
return radius == circle.radius;
}
return false;
}
@Override
public String toString() {
return "半径为" + radius;
}
}
public class Test {
public static void main(String[] args) {
Circle circle1 = new Circle(1.0, "红色");
Circle circle2 = new Circle(2.0, "蓝色");
if (circle1.getColor().equals(circle2.getColor())) {
System.out.println("两个圆形的颜色相同");
} else {
System.out.println("两个圆形的颜色不同");
}
if (circle1.equals(circle2)) {
System.out.println("两个圆形的半径相等");
} else {
System.out.println("两个圆形的半径不等");
}
System.out.println("圆形1的" + circle1.toString());
System.out.println("圆形2的" + circle2.toString());
}
}
```
输出结果:
```
两个圆形的颜色不同
两个圆形的半径不等
圆形1的半径为1.0
圆形2的半径为2.0
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)