day09-接口多态的笔记本案例

This commit is contained in:
2026-01-25 14:02:32 +08:00
parent 8da93fa501
commit f9af5aaace
5 changed files with 120 additions and 0 deletions

View 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();
}
}

View File

@@ -0,0 +1,35 @@
package com.inmind.duotai08.test2;
/*
笔记本电脑laptop通常具备使用USB设备的功能。
在生产时笔记本都预留了可以插入USB设备的USB接口但具体是什么USB设备笔记本厂商并不关心只要符合USB规格的设备都可以。
定义USB接口具备最基本的开启功能和关闭功能。
鼠标和键盘要想能在电脑上使用那么鼠标和键盘也必须遵守USB规范实现USB接口否则鼠标和键盘的生产出来也无法使用。
进行描述笔记本类实现笔记本使用USB鼠标、USB键盘
使用USB鼠标、USB键盘将一类USB设备可以传递给电脑进行使用其实就是定义一个方法接收USB类型多态
USB接口包含开启功能、关闭功能
笔记本类包含运行功能、关机功能、使用USB设备功能
鼠标类要实现USB接口并具备点击的方法
键盘类要实现USB接口具备敲击的方法
*/
public class Demo13 {
public static void main(String[] args) {
//现实中先买一台电脑
Computer computer = new Computer();
//再买个键盘和鼠标
KeyBoard keyBoard = new KeyBoard();
Mouse mouse = new Mouse();
//电脑开机
computer.powerOn();
//使用电脑使用USB设备
computer.useUsbDevice(mouse);
computer.useUsbDevice(keyBoard);
//玩了一伙,关机吃饭
computer.closeUsbDevice(keyBoard);
computer.closeUsbDevice(mouse);
computer.powerOff();
}
}

View File

@@ -0,0 +1,18 @@
package com.inmind.duotai08.test2;
//键盘类要实现USB接口具备敲击的方法
public class KeyBoard implements Usb{
@Override
public void open() {
System.out.println("键盘启动了");
}
@Override
public void close() {
System.out.println("键盘关闭了");
}
//接口实现类的独有的功能
public void knock(){
System.out.println("键盘敲击输入内容");
}
}

View File

@@ -0,0 +1,19 @@
package com.inmind.duotai08.test2;
//鼠标类要实现USB接口并具备点击的方法
public class Mouse implements Usb{
@Override
public void open() {
System.out.println("鼠标启动了");
}
@Override
public void close() {
System.out.println("鼠标关闭了");
}
//独有的功能
public void click(){
System.out.println("鼠标点击了");
}
}

View File

@@ -0,0 +1,6 @@
package com.inmind.duotai08.test2;
//USB接口包含开启功能、关闭功能
public interface Usb {
public abstract void open();
void close();
}