接口主要是为了向上转型,从而使基类(接口方法)更具灵活性!不想废话,看例子:
/** * */ package interfaces; interface Monster{ void menace(); } interface DangerousMonster extends Monster{ void destory(); } interface Lethal{ void kill(); } class DragonZilla implements DangerousMonster{ public void menace(){ System.out.println("DangerousMonster menace()"); } public void destory(){ System.out.println("DangerousMonster destory()"); } } interface Vampire extends DangerousMonster,Lethal{ void drinkBlood(); } class VeryBadVampire implements Vampire{ public void menace(){ System.out.println("VeryBadVampire menace()"); } public void destory() { // TODO Auto-generated method stub System.out.println("VeryBadVampire destroy()"); } public void kill() { // TODO Auto-generated method stub System.out.println("VeryBadVampire kill()"); } public void drinkBlood() { System.out.println("VeryBadVampire dinrkBlood()"); } } public class HorrorShow { static void u(Monster b){b.menace();} static void v(DangerousMonster d){ d.menace(); d.destory(); } static void w(Lethal l){ l.kill(); } public static void main(String[] args) { // TODO Auto-generated method stub DangerousMonster barney = new DragonZilla(); u(barney); v(barney); Vampire Vlad = new VeryBadVampire(); u(Vlad); v(Vlad); w(Vlad); } }
DangerousMonster menace()
DangerousMonster menace()
DangerousMonster destory()
VeryBadVampire menace()
VeryBadVampire menace()
VeryBadVampire destroy()
VeryBadVampire kill()
原文:http://www.cnblogs.com/fxyfirst/p/3778629.html