Ric*_*ick 2 java constructor constructor-chaining
我正在做一个Yahtzee游戏.我想为不同的情况提供构造函数.假设您无法提供想要创建新游戏的玩家的名字,我想创建"未命名玩家1","未命名玩家2"等.
这是我试图这样做的方式:
public class YahtzeeGame {
private List<Player> players = new ArrayList<>();
public YahtzeeGame(String[] playerNames) {
for (String playerName : playerNames) {
players.add(new Player(playerName));
}
}
public YahtzeeGame(int numberOfPlayers) {
String[] playerNames = new String[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
playerNames[i] = "Unnamed player " + (i+1);
}
this(playerNames); // ERROR: "Constructor call must be the first statement in a constructor.
}
public YahtzeeGame(String playerName) {
this(new String[] {playerName});
}
public YahtzeeGame() {
this("Unnamed player");
}
}
Run Code Online (Sandbox Code Playgroud)
根据评论中写的错误,这当然不起作用.
有没有解决的办法?我需要一个工厂模式吗?
是的,有一个相当简单的方法,至少在这种情况下:创建一个静态方法,它将为您准备构造函数参数.从this表达式中调用:
public YahtzeeGame(int numberOfPlayers) {
this(getUnnamedPlayers(numberOfPlayers));
}
private static String[] getUnnamedPlayers(int numberOfPlayers) {
String[] playerNames = new String[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
playerNames[i] = "Unnamed player " + (i+1);
}
return playerNames;
}
Run Code Online (Sandbox Code Playgroud)
请注意,它必须是静态的,因为您不能this在链式构造函数之前调用任何实例方法.