通过ArrayList

时间:2016-05-16 15:18:19

标签: java casting subclass

我在Game类中有一个玩家的ArrayList。玩家可以扮演人类或cpu的角色。所以我有类Human和CPU扩展了Player的类

public class Game{
    private ArrayList<Player> _list;
    Game(){
        _list=new ArrayList<Player>();
    }
    //**********
    void doSomething(){
        for(int i=0;i<_list.size();i++){
            Player q=_list.get(i);
            if(q is instaceof CPU) //I'd like to call a CPU method
            else //I'd like to call a Human method
        }

    }
}

public abstract class Player{
    private String name;

    Player(string name2){
        name=name;
   }
    //********** more methods

}

pulic class Human extends Player{
    public Human(String name){ 
        super(name);
    }
    void methodHuman();       
}

public class CPU extends Player{
    public CPU (String name){
        super(name);
    } 
    void methodCPU();
}

如何调用子类的方法?我必须做演员吗?

0 个答案:

没有答案