interface的理解

来源:互联网 发布:淘宝tiffany代购 编辑:程序博客网 时间:2024/04/29 21:48
interface的理解

入门级

一个简单的接口例子:

public interface Weapon {
    public void attack();
}
public class Tank implements Weapon {

    public void attack() {
        System.out.println("Tank Fire Cannon");
    }
}
/* 洲际导弹*/
public class ICBM implements Weapon {

    public void attack() {
        System.out.println("ICBM Sending");
    }
}
/* 战斗机*/
public class BattlePlane implements Weapon {

    public void attack() {
        System.out.println("Battle Plane firing");
    }
}
/*武器控制台*/
public class WeaponConsole {

    public void openFire(Weapon w) {
        //注意下面两行被注释的语句和第3行是等效的
        //Weapon weapon = (Weapon)w;
        //weapon.attack();
        w.attack();
    }

    public static void main(String[] args) {
        System.out.println("ready.....");
        WeaponConsole c = new WeaponConsole();
        c.openFire(new Tank());
        c.openFire(new BattlePlane());
        c.openFire(new ICBM());
    }
}
最后执行结果是:

ready.....
Tank Fire Cannon
Battle Plane firing
ICBM Sending
我以中文名再一次举重复的例子,这样可能对被字符迷惑的初学者有所帮助。

public interface 武器 {
    public void 攻击();
}
public class 坦克 implements 武器 {

    public void 攻击() {
        System.out.println("坦克 发炮!");
    }
}
public class 战斗机 implements 武器 {

    public void 攻击() {
        System.out.println("战斗机 轰炸!");
    }
}
public class 洲际导弹 implements 武器 {

    public void 攻击() {
        System.out.println("洲际导弹 发射!");
    }
}
public class 武器控制台 {

    public void 开火(武器 w) {
        w.攻击();
    }

    public static void main(String[] args) {
        System.out.println("准备进攻.....");
        武器控制台 c = new 武器控制台();
        c.开火(new 坦克());
        c.开火(new 战斗机());
        c.开火(new 洲际导弹());
    }
}
编译并执行:

>;javac *.class
>;java 武器控制台
最后执行结果是:

准备进攻.....
坦克 发炮!
战斗机 轰炸!
洲际导弹 发射! 
原创粉丝点击