我有一个名为Game的超级类,它包含一个函数pickPlayers()
和一个ArrayList<Player> players
,其中包含所选的函数,以及一个扩展它的子类ConsoleGame
。问题是当我创建ConsoleGame
的实例并调用myInstance.pickPlayers()
时,实例的arraylist播放器为空。有任何想法吗?我认为这主要是一个概念性问题,但如果有帮助,这里有一些代码:
这是课程游戏:
import java.util.ArrayList;
public abstract class Game {
protected String name;
protected int numPlayers;
protected ArrayList<Player> players;
public Game(String n, int np) {
name = n;
numPlayers = np;
}
protected void pickPlayers(ArrayList<Player> players) {
/**
* Choose players at random from the array passed in to play the game
* Parameters:
* ArrayList<Player> players - the array of players
* Returns:
* void
*/
// choose players at random from players to play the game
for(int j = 0; j < numPlayers; j++) {
players.add(players.get(GameNight.generator.nextInt(players.size() - 1)));
}
}
protected abstract void play();
}
这里是BoardGame的子类:
public class BoardGame extends Game {
/**
* Luck factor of the game
*/
private double luckFactor;
/**
* Constructor, takes three args to set the instance variables
* @param n Name of the game
* @param np Number of players that can play the game at once
* @param l Luck factor
*/
public BoardGame(String n, int np, double l) {
super(n,np);
luckFactor = l;
}
/**
* Plays the game and chooses a winner. Winner is chosen to be
* the person with the largest value of
* intelligence + (luck * luckFactor), where luck refer's to the
* Player's luckiness and luckFactor refers to the Game's instance
* variable. This method returns nothing but does call youWin()
* on the Player that won the game.
*/
public void play() {
// code here
}
}
答案 0 :(得分:2)
public void pickPlayers(ArrayList<Player> players) {
players.get(..)
}
它引用了局部变量,你是shadowing你的实例变量。要使用实例属性,您必须使用this
进行引用
那就是。
this.players.get(..)
注意强>
顺便提一下,当您创建游戏类型时,players
为空。可能是你应该初始化为空列表。