您的位置:首页 > 编程语言 > Java开发

Java标识接口

2016-03-10 17:05 447 查看
在接口内部没有声明任何方法,叫做标识接口。相当于一个标签可以标记实现类,一个类可以实现多个标记类来实现给自己打多个标签的目的。结合instanceof运算符可以实现一些功能。JAVA里很多类实现了Cloneable、Serializable接口不就是表明这个类可以克隆序列化。应用上比如游戏里收集材料,需要掉矿石和武器,过滤掉垃圾。

import java.util.ArrayList;

interface Stuff{}

interface Ore extends Stuff{}

interface Weapon extends Stuff{}

interface Rubbish extends Stuff{}

class Gold implements Ore{

    public String toString(){

        return "Gold";

    }

}

class Copper implements Ore{

    public String toString(){

        return "Copper";

    }

}

class Gun implements Weapon{

    public String toString(){

        return "Gun";

    }

}

class Grenade implements Weapon{

    public String toString(){

        return "Grenade";

    }

}

class Stone implements Rubbish{

    public String toString(){

        return "Stone";

    }

}

public class OreWeaponGold {

    

    public static ArrayList<Stuff> collectStuff(Stuff[] s){

        

        ArrayList<Stuff> al = new ArrayList<Stuff>();

        

        for( int i = 0; i < s.length; i++ ){

            

            if(!(s[i] instanceof Rubbish ))

                al.add(s[i]);

            

        }

        

        return al;

        

    }

    

    public static void main(String[] args) {

        Stuff[] s = { new Gold(), new Copper(), new Gun(), new Grenade(), new Stone()};

        ArrayList<Stuff> al = collectStuff(s);

        System.out.println("The usefull Stuff collected is: ");

        for( int i = 0; i < al.size(); i++){

            System.out.println( al.get(i) );

        }

    }

}

输出:

The usefull Stuff collected is:

Gold

Copper

Gun

Grenade
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: