设计一个名为Fan的类来代表风扇。这个类包括三个常量SLOW,MEDIUM和FAST,其值分别为1,2,3,表示风扇的速度

156 阅读2分钟

不要自卑,去提升实力
互联网行业谁技术牛谁是爹
如果文章可以带给你能量,那是最好的事!请相信自己,加油o~

题目描述:

设计一个名为Fan的类来代表风扇。这个类包括:
1 三个常量SLOW,MEDIUM和FAST,其值分别为1,2,3,表示风扇的速度;
2 int类型的数据域speed表示风扇的速度;默认值为SLOW
3 boolean型的数据域on表示风扇是否打开;默认值为false
4 double型的数据域radius表示风扇的半径;默认值为5
5 string型的数据域color表示风扇的颜色;默认值为blue
6 无参构造方法创建默认风扇;
7 全部四个数据域的访问器和修改器;
9 toString()方法返回描述风扇的字符串。如果风扇打开,该方法用一个组合的字符串返回风扇的速度,颜色和半径;否则,用一个组合的字符串和“fan is off”一起返回风扇的颜色和半径。
画出该类的UML图并实现它。编写一个测试程序,创建两个Fan对象,将第一个对象设置为最大速度,半径为10,颜色为yellow,打开状态;第二个对象为中等速度,半径为5,颜色blue,关闭状态。通过调用toString方法显示该对象。

代码:

/**
 *作者:魏宝航
 *2020年11月27日,下午10:41
 */
package 测试;
import java.util.*;
public class Test{
	public static void main(String[] args) {
		Fan fan1=new Fan();
		Fan fan2=new Fan();
		fan1.setSpeed(Fan.FAST);
		fan1.setRadius(10);
		fan1.setColor("yellow");
		fan1.setOn(true);
		fan2.setSpeed(Fan.MEDIUM);
		fan2.setRadius(5);
		fan2.setColor("blue");
		fan2.setOn(false);
		System.out.println(fan1.toString());
		System.out.println(fan2.toString());
	}
}
class Fan{
	static final int SLOW=1;
	static final int MEDIUM=2;
	static final int FAST=3;
	private int speed=SLOW;
	private boolean on=false;
	private double radius=5;
	private String color="blue";
	public Fan() {}
	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;
	}
	@Override
	public String toString() {
		if(!on) {
			return "fan is off";
		}
		return "风扇的速度:"+speed+"\n颜色:"+color+"\n半径:"+radius;
	}
}