java接口
本文指标:
1.java接口应用案例
2.为什么设计java接口
java接口应用案例:
package com.wt010.myinterface; /** * @author konecms * @date 2018年1月7日 * @version 1.0 */ interface USB { void install(); void work(); }
package com.wt010.myinterface; /** * @author konecms * @date 2018年1月7日 * @version 1.0 */ public class Phone implements USB { public void install(){ System.out.println("phone's USB intalled"); } public void work(){ System.out.println("phone is working ."); } }
package com.wt010.myinterface; /** * @author konecms * @date 2018年1月7日 * @version 1.0 */ public class MP3 implements USB { public void install(){ System.out.println("MP3's USB installed"); } public void work(){ System.out.println("MP3 is working"); } }
package com.wt010.myinterface; /** * @author konecms * @date 2018年1月7日 * @version 1.0 */ public class Computer { public void plugin(USB u){ u.install(); u.work(); } }
package com.wt010.myinterface; /** * @author konecms * @date 2018年1月7日 * @version 1.0 */ public class InterfaceUSBDEMO { public static void main(String[] args) { Computer c=new Computer(); c.plugin(new Phone()); c.plugin(new MP3()); } }
为什么设计java接口?
我觉得本质的原因在于:java抽象类与派生类是“ 是不是”的关系;接口与实现它的类是 “有没有”的关系,比如动物是狗,猫,鸟等具象的抽象类(相对的),而飞翔这一行为可以做成一个接口,有这个行为的动物就去实现它。