接口使用,举例配置一个简易的计算机:
1.定义一个显卡的接口:
interface VideoCard{ void display(); String getName(); }
2.定义一个Cpu的接口:
interface PCPU{ void run(); String getName(); }
3.实现显卡接口:
class ThreeColor implements VideoCard{ String name; public ThreeColor(){ name="Three Color Inc."; } public void display(){ System.out.println("Three Color's VideoCard is working"); } public String getName(){ return name; } }
4.实现Cpu接口:
class Core4Intel implements PCPU{ String name; Core4Intel(){ name = "Intel inc"; } public void run(){ System.out.println("Cpu is running"); } public String getName(){ return name; } }
5.定义主板,并使用显卡和cpu的接口:
class Mainboard{ VideoCard vc; PCPU cpu; String name; Mainboard(){ name= "Chen bin de mainboard"; } void setVideoCard(VideoCard vc){ this.vc = vc; } void setCpu(PCPU cpu){ this.cpu = cpu; } void run(){ System.out.println(name); System.out.println(cpu.getName()); cpu.run(); System.out.println(vc.getName()); vc.display(); System.out.println("mainboard is working"); } }
6.定义计算机,并实例化显卡,Cpu
class Computer{ public static void main(String[] args){ Mainboard m = new Mainboard(); ThreeColor t= new ThreeColor(); Core4Intel c = new Core4Intel(); m.setCpu(c); m.setVideoCard(t); m.run(); } }
7.看看结果:
接口和抽象类的区别:
接口是公开的,里面不能有私有的方法或变量,是用于让别人使用的,而抽象类是可以有私有方法或私有变量的,
另外,实现接口的一定要实现接口里定义的所有方法,而实现抽象类可以有选择地重写需要用到的方法,一般的应用里,最顶级的是接口,然后是抽象类实现接口,最后才到具体类实现。
还有,接口可以实现多重继承,而一个类只能继承一个超类,但可以通过继承多个接口实现多重继承,接口还有标识(里面没有任何方法,如Remote接口)和数据共享(里面的变量全是常量)的作用.