package com.test;
/*
面向接口编程:多态的好处:把实现类对象赋给接口类型变量,屏蔽了不同实现类之间的差异,
从而可以做到通用编程 案例:使用USB设备来工作。
*/
//指定USB规范
interface IUSB{
void swapData();
}
class Mouse implements IUSB{
public void swapData(){
System.out.println("鼠标在移动");
}
}
//USB版本打印机
class Print implements IUSB{
public void swapData(){
System.out.println("打印,嘟嘟嘟....");
}
}
//主板
class MotherBoard {
//把设备插入到主板中的功能,接受IUSB类型的对象
public static void pluginIn(IUSB m){
m.swapData();
}
}
public class InterfacePratice {
public static void main(String[] args){
//鼠标
Mouse m=new Mouse();
MotherBoard.pluginIn(m);//类中的静态方法可以直接:类名.方法名
//安装打印机
Print p=new Print();
MotherBoard.pluginIn(p);
}
}
改进:
package com.test;
/*
面向接口编程:多态的好处:把实现类对象赋给接口类型变量,屏蔽了不同实现类之间的差异,
从而可以做到通用编程 案例:使用USB设备来工作。
*/
//指定USB规范
interface IUSB{
void swapData();
}
class Mouse implements IUSB{
public void swapData(){
System.out.println("鼠标在移动");
}
}
//USB版本打印机
class Print implements IUSB{
public void swapData(){
System.out.println("打印,嘟嘟嘟....");
}
}
//主板
class MotherBoard {
private static IUSB[] usbs=new IUSB[6];
private static int index=0;
//把设备插入到主板中的功能,接受IUSB类型的对象
public static void pluginIn(IUSB usb){
if(index == usbs.length){
System.out.println("usb插满!");
return;
}
usbs[index++]=usb;
}
//取出主板中的每一个USB设备,并工作
public static void doWork(){
for(IUSB usb:usbs){
if(usb != null){
usb.swapData();
}
}
}
}
public class InterfacePratice {
public static void main(String[] args){
//鼠标
Mouse m=new Mouse();
MotherBoard.pluginIn(m);//类中的静态方法可以直接:类名.方法名
//安装打印机
Print p=new Print();
MotherBoard.pluginIn(p);
//调用主板的工作行为
MotherBoard.doWork();
}
}