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
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
相关文章推荐
- 详解java定时任务
- Spring MVC学习笔记02
- JAVA学习篇--javaweb之Filter具体解释
- eclipse as android jni 和 ndk以及调用过程--tread
- JAVA关于时间的处理
- HDU 1250 Hat's Fibonacci (JAVA大数)
- 继承JPanel的类不显示
- Java开发中的23种设计模式详解
- 自定义的RPC的Java实现
- Java基础学习总结(51)——JAVA分层理解
- Java基础学习总结(51)——JAVA分层理解
- 【java-之路】序列化与反序列化对象
- java递归删除文件夹demo,删除文件目录例子
- java回调机制详解
- java时间戳与Date(String)相互转化
- Spring+dubbo+mybatis出现NoSuchMethodError和MutablePropertyValues.add异常
- Spring+dubbo+mybatis出现NoSuchMethodError和MutablePropertyValues.add异常
- java对cookie的操作
- 那些年spring声明式事务@Transaction的坑
- java实现大整数的四则运算