创建两个电扇对象,打开第一个电扇,风速、半径、颜色设置为FAST、10、yellow;第二个电扇以默认值创建并将风速设置为MEDIUM。分别调用toString方法输出电扇信息
时间: 2024-01-29 15:04:22 浏览: 16
好的,我可以帮你实现这个功能。以下是示例代码:
```java
public class Fan {
private int speed;
private boolean on;
private double radius;
private String color;
public static final int SLOW = 1;
public static final int MEDIUM = 2;
public static final int FAST = 3;
public Fan() {
speed = SLOW;
on = false;
radius = 5;
color = "blue";
}
public String toString() {
if (on) {
return String.format("speed: %d, color: %s, radius: %.1f", speed, color, radius);
} else {
return String.format("color: %s, radius: %.1f, fan is off", color, radius);
}
}
// getters and setters
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
```
然后你可以在主函数中创建两个Fan对象,并按照要求设置属性:
```java
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setOn(true);
fan1.setSpeed(Fan.FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
Fan fan2 = new Fan();
fan2.setSpeed(Fan.MEDIUM);
System.out.println("Fan 1: " + fan1.toString());
System.out.println("Fan 2: " + fan2.toString());
}
```
运行结果如下:
```
Fan 1: speed: 3, color: yellow, radius: 10.0
Fan 2: color: blue, radius: 5.0, fan is off
```
请注意,Fan类中的toString方法只返回风扇的基本信息,你可以根据需要进行修改。另外,如果你想让Fan类更加灵活,可以添加其他的属性和方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://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://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)