所以我有这个课:
public class x {
ConsoleIO io = new ConsoleIO();
private Board board;
private boolean playing;
public x (String een, String twee) {
this.board = new Board();
if (een.toUpperCase().equals("C")) {
Computer speler1 = new Computer(een);
} else {
Player speler1 = new Player(een);
}
if (twee.toUpperCase().equals("C")) {
this.speler2 = new Computer(twee);
} else {
this.speler2 = new Player(twee);
}
this.playing = true;
}
}
如您所见,我想根据我提供的输入来初始化变量speler1&speler2。
显然,这是行不通的。我知道我应该像这样初始化变量:
public class x {
ConsoleIO io = new ConsoleIO();
private Board board;
private boolean playing;
private Player speler1;
private Player speler2;
但是后来我仅限于播放器类型,我不想要那样。有没有办法正确地做到这一点?
*注:计算机是播放器的延伸。
最佳答案
我的建议是声明一个Object
:
private Object speler1;
然后在您的if条件中:
speler1 = new Computer(een);
要么
speler1 = new Player(een);
现在,当您需要使用speler1时,只需使用如下检查
// if(speler1 instanceof Computer)
if(speler1 instanceof Player)
player1 = (Player)speler1;