day10-接口多态的笔记本案例
This commit is contained in:
42
day10/src/com/inmind/duotai08/test2/Computer.java
Normal file
42
day10/src/com/inmind/duotai08/test2/Computer.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.inmind.duotai08.test2;
|
||||
/*
|
||||
笔记本类,包含运行功能、关机功能、使用USB设备功能
|
||||
实现笔记本使用USB鼠标、USB键盘
|
||||
使用USB鼠标、USB键盘:将一类USB设备可以传递给电脑,进行使用,其实就是定义一个方法接收USB类型(多态)
|
||||
*/
|
||||
public class Computer {
|
||||
//运行功能
|
||||
public void powerOn(){
|
||||
System.out.println("电脑开机了");
|
||||
}
|
||||
|
||||
//关机功能
|
||||
public void powerOff(){
|
||||
System.out.println("电脑关机了");
|
||||
}
|
||||
|
||||
//使用USB设备功能
|
||||
//具体是什么USB设备,笔记本并不关心,只要符合USB规格的设备都可以
|
||||
public void useUsbDevice(Usb usbDevice){//接口的多态:Usb usbDevice = new 键盘、鼠标、U盘等USB设备对象;(向上转型)
|
||||
if (usbDevice == null) {
|
||||
System.out.println("您使用的USB设备不存在");
|
||||
return;
|
||||
}
|
||||
|
||||
usbDevice.open();
|
||||
//必须先向下转型
|
||||
if (usbDevice instanceof KeyBoard) {
|
||||
KeyBoard keyBoard = (KeyBoard) usbDevice;
|
||||
keyBoard.knock();
|
||||
}
|
||||
|
||||
if (usbDevice instanceof Mouse) {
|
||||
Mouse mouse = (Mouse) usbDevice;
|
||||
mouse.click();
|
||||
}
|
||||
}
|
||||
|
||||
public void closeUsbDevice(Usb usbDevice) {
|
||||
usbDevice.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user