要求:文章来源:https://www.toymoban.com/news/detail-601480.html
请实现笔记本电脑使用USB鼠标、USB键盘的例子 文章来源地址https://www.toymoban.com/news/detail-601480.html
package csdn;
import javax.swing.*;
public class computer {
public void powerOn(){
System.out.println("打开笔记本电脑");
}
public void powerOff(){
System.out.println("关闭笔记本电脑");
}
public void useDevice(IUSB iusb){
iusb.openDevice(); //打开服务
if(iusb instanceof Mouse){
Mouse mouse=(Mouse)iusb; //向下转型
mouse.click();
}else if(iusb instanceof keyBoard){
keyBoard keyBoard=(keyBoard)iusb; //向下转型
keyBoard.input();
}
iusb.closeDevice(); //关闭服务
}
}
package csdn;
public interface IUSB {
void openDevice(); //打开服务
void closeDevice(); //关闭服务
}
package csdn;
public class keyBoard implements IUSB {
@Override
public void openDevice() {
System.out.println("打开键盘");
}
@Override
public void closeDevice() {
System.out.println("关闭键盘");
}
public void input(){
System.out.println("敲击键盘输入");
}
}
package csdn;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
public class Mouse implements IUSB {
@Override
public void openDevice() {
System.out.println("打开鼠标服务");
}
@Override
public void closeDevice() {
System.out.println("关闭鼠标服务");
}
public void click(){
System.out.println("点击鼠标");
}
}
package csdn;
public class test {
public static void main(String[] args) {
computer computer=new computer();
Mouse mouse=new Mouse();
keyBoard keyBoard=new keyBoard();
computer.useDevice(mouse); //向上转型
System.out.println("===========");
computer.useDevice(keyBoard); //向上转型
}
}
到了这里,关于【Java】一个简单的接口例子(帮助理解接口+多态)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!