在接口内部没有声明任何方法,叫做标识接口。相当于一个标签可以标记实现类,一个类可以实现多个标记类来实现给自己打多个标签的目的。结合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