模拟实现电风扇,可以调3档速度(慢速、中速、快速);开关按钮;定时吹风;描述风扇的扇叶大小、颜色等。 设计Fan类,属性包括:3个常量SLOW(1)、MEDIUM(2)、FAST(3)代表风扇的速度;1个int属性speed指定速度,默认值为SLOW;1个boolean属性on指定开关机,默认值false;1个double属性radius指定风扇扇叶大小;1个String属性color指定扇叶颜色,默认值为blue。方法包括这些属性的访问器、构造函数、重写Object类的toString()和equals()方法等。运行测试代码: public static void main(String[] args) { Fan1 fan1 = new Fan1(); fan1.setSpeed(Fan1.FAST); fan1.setRadius(10); fan1.setColor("yellow"); fan1.setOn(true); System.out.println(fan1.toString()); }
时间: 2024-03-24 15:38:55 浏览: 25
好的,以下是Fan类的实现:
```java
public class Fan {
public static final int SLOW = 1;
public static final int MEDIUM = 2;
public static final int FAST = 3;
private int speed;
private boolean on;
private double radius;
private String color;
public Fan() {
this.speed = SLOW;
this.on = false;
this.radius = 5.0;
this.color = "blue";
}
public int getSpeed() {
return this.speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public boolean isOn() {
return this.on;
}
public void setOn(boolean on) {
this.on = on;
}
public double getRadius() {
return this.radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
if (this.on) {
return "Fan is on. Speed: " + this.speed + ", Color: " + this.color + ", Radius: " + this.radius;
} else {
return "Fan is off. Color: " + this.color + ", Radius: " + this.radius;
}
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Fan other = (Fan) obj;
return this.speed == other.speed && this.on == other.on && this.radius == other.radius && this.color.equals(other.color);
}
}
```
在这个类中,我们定义了常量SLOW、MEDIUM和FAST,它们分别代表风扇的3档速度。然后,我们定义了4个属性,它们分别是速度、开关机、扇叶大小和扇叶颜色。在Fan类的构造函数中,我们设置了初始值,速度为SLOW,开关机为关,扇叶大小为5.0,扇叶颜色为blue。
接下来,我们定义了访问器和设置器,分别用于获取和设置属性。在toString方法中,我们根据开关机状态打印不同的字符串。在equals方法中,我们比较了所有属性的值。
最后,我们可以运行测试代码,创建一个Fan对象,设置各种属性,并打印输出Fan对象的信息:
```java
public static void main(String[] args) {
Fan fan = new Fan();
fan.setSpeed(Fan.FAST);
fan.setRadius(10);
fan.setColor("yellow");
fan.setOn(true);
System.out.println(fan.toString());
}
```
输出结果为:
```
Fan is on. Speed: 3, Color: yellow, Radius: 10.0
```