Create a class called Fan.java to represent a fan. The class contains: Three con
ID: 653368 • Letter: C
Question
Create a class called Fan.java to represent a fan. The class contains:
Three constants named SLOW, MEDIUM, and FAST with the values 1, 2, and 3 to denote the fan speed.
A private int data field named speed that specifies the speed of the fan (the default is SLOW).
A private boolean data field named on that specifies whether the fan is on (the default is false).
A private double data field named radius that specifies the radius of the fan (the default is 5).
A string data field named color that specifies the color of the fan (the default is blue).
The accessor and mutator methods for all four data fields.
A no-arg constructor that creates a default fan.
A method named toString() that returns a string description for the fan. If the fan is on, the method returns the fan speed, color, and radius in one combined string. If the fan is not on, the method returns the fan color and radius along with the string "fan is off" in one combined string.
Then create a test program called TestFan.java that creates two Fan objects. For the first Fan object, assign maximum speed, radius 10, color yellow, and turn it on. For the second Fan object, assign medium speed, radius 5, colorblue, and turn it off. Display the objects by invoking their toString() method.
Explanation / Answer
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 = 3;
private boolean on = false;
private double radius = 5;
String color = "blue";
public int getSpeed() {
return speed;
}
public boolean isOn() {
return on;
}
public double getRadius() {
return radius;
}
public String getColor() {
return color;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setOn(boolean on) {
this.on = on;
}
public void setRadius(double radius) {
this.radius = radius;
}
public void setColor(String color) {
this.color = color;
}
public Fan() {
super();
}
@Override
public String toString() {
if (isOn())
return "Fan is On [speed=" + speed + ", radius=" + radius
+ ", color=" + color + "]";
else
return "Fan is OFF [radius=" + radius + ", color=" + color + "]";
}
}
TestFan.java
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setSpeed(Fan.FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.setOn(true);
Fan fan2 = new Fan();
fan2.setSpeed(Fan.MEDIUM);
fan2.setRadius(5);
fan2.setColor("blue");
fan2.setOn(false);
System.out.println(fan1);
System.out.println(fan2);
}
}
Sample out put:
Fan is On [speed=3, radius=10.0, color=yellow]
Fan is OFF [radius=5.0, color=blue]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.