定义USB接口
package com.pp;
public interface USB {
void open();//开启功能
void close();//关闭功能
}
定义笔记本类
package com.pp;
public class NoteBook {
public void run(){
System.out.println("笔记本运行");
}
public void useUSB(USB usb){
if(usb!=null){
usb.open();
usb.close();
}
}
public void ShutDown(){
System.out.println("笔记本关闭");
}
}
定义键盘类
package com.pp;
public class KeyBoard implements USB {
@Override
public void open() {
System.out.println("键盘开启");
}
@Override
public void close() {
System.out.println("键盘关闭");
}
}
定义鼠标类
package com.pp;
public class Mouse implements USB {
@Override
public void open() {
System.out.println("鼠标开启");
}
@Override
public void close() {
System.out.println("鼠标关闭");
}
}
测试类
package com.pp;
public class Test {
public static void main(String[] args) {
NoteBook noteBook = new NoteBook();//创建笔记本实体对象
noteBook.run();//开启笔记本
Mouse mouse = new Mouse();//创建鼠标实体对象
noteBook.useUSB(mouse);//笔记本使用鼠标
KeyBoard keyBoard = new KeyBoard();//创建键盘实体对象
noteBook.useUSB(keyBoard);//笔记本使用键盘
noteBook.ShutDown();//关闭笔记本
}
}
运行结果如下图所示:
笔记本运行
鼠标开启
鼠标关闭
键盘开启
键盘关闭
笔记本关闭
Process finished with exit code 0