package 多态;标签:System,usb,void,多态,name,实例,public,USB From: https://www.cnblogs.com/mqsjy/p/17278469.html
//USB接口
//定义USB的规范,必须要完成接入和拔出的功能
//定义2个USB设备,鼠标,键盘
interface USB {
void connect();//接入
void unconnect();//拔出
}
class Mouse implements USB{
private String name;
public Mouse(String name){
this.name = name;
}
//双击方法
public void dbclick(){
System.out.println("双击");
}
@Override
public void unconnect() {
System.out.println("成功的拔出了电脑");
}
@Override
public void connect() {
System.out.println("成功的接入了电脑");
}
}
class Keyboard implements USB{
private String name;
public Keyboard(String name) {
this.name = name;
}
//按键方法
public void keyDown(){
System.out.println("按键,写下了");
}
@Override
public void connect() {
System.out.println("成功的接入了电脑");
}
@Override
public void unconnect() {
System.out.println("成功的拔出了电脑");
}
}
class Computer{
//提供一个安装USB设备的入口
public void install(USB usb){
usb.connect();
//usb可能是鼠标,也可能是键盘,一下作做判断
if(usb instanceof Mouse){
Mouse m = (Mouse) usb;
m.dbclick();
}else if(usb instanceof Keyboard){
Keyboard k = (Keyboard)usb;
k.keyDown();
}
usb.unconnect();
}
}
class Test{
public static void main(String[] args) {
Computer c = new Computer();
USB xiaomi = new Mouse("小米鼠标");
c.install(xiaomi);
USB luoji = new Keyboard("罗技");
c.install(luoji);
}
}