java模拟设备管理键盘鼠标打印机显示器
时间: 2023-08-22 20:03:25 浏览: 41
首先,你需要定义一个设备类,包括设备名称、设备类型和设备状态等属性,并实现设备的操作方法。
以下是一个简单的设备类的示例代码:
```java
public class Device {
private String name;
private String type;
private boolean status;
public Device(String name, String type) {
this.name = name;
this.type = type;
this.status = false;
}
public void turnOn() {
this.status = true;
System.out.println(this.name + " is turned on.");
}
public void turnOff() {
this.status = false;
System.out.println(this.name + " is turned off.");
}
public boolean getStatus() {
return this.status;
}
public String getType() {
return this.type;
}
public String getName() {
return this.name;
}
}
```
接下来,你可以创建具体的设备类,例如键盘、鼠标、打印机和显示器等。
以下是一个键盘类的示例代码:
```java
public class Keyboard extends Device {
public Keyboard(String name, String type) {
super(name, type);
}
public void type(String content) {
if (this.getStatus()) {
System.out.println("Input: " + content);
} else {
System.out.println("Keyboard is turned off.");
}
}
}
```
以下是一个鼠标类的示例代码:
```java
public class Mouse extends Device {
public Mouse(String name, String type) {
super(name, type);
}
public void click() {
if (this.getStatus()) {
System.out.println("Mouse clicked.");
} else {
System.out.println("Mouse is turned off.");
}
}
}
```
以下是一个打印机类的示例代码:
```java
public class Printer extends Device {
private String paper;
public Printer(String name, String type) {
super(name, type);
this.paper = "";
}
public void print(String content) {
if (this.getStatus()) {
this.paper += content;
} else {
System.out.println("Printer is turned off.");
}
}
public void showPaper() {
System.out.println("Paper: " + this.paper);
}
}
```
以下是一个显示器类的示例代码:
```java
public class Monitor extends Device {
private String screen;
public Monitor(String name, String type) {
super(name, type);
this.screen = "";
}
public void display(String content) {
if (this.getStatus()) {
this.screen += content;
System.out.println("Display: " + this.screen);
} else {
System.out.println("Monitor is turned off.");
}
}
}
```
最后,你可以在主函数中创建这些设备,并进行操作。
以下是一个简单的主函数的示例代码:
```java
public static void main(String[] args) {
Keyboard keyboard = new Keyboard("Keyboard", "Input");
Mouse mouse = new Mouse("Mouse", "Input");
Printer printer = new Printer("Printer", "Output");
Monitor monitor = new Monitor("Monitor", "Output");
keyboard.turnOn();
mouse.turnOn();
printer.turnOn();
monitor.turnOn();
keyboard.type("Hello world!");
mouse.click();
printer.print("This is a test.");
monitor.display("Welcome to Java World!");
printer.showPaper();
}
```