构造函数在调用之前链接并准备参数(aguments)

时间:2018-01-30 15:36:23

标签: 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");
    }
}

当然,根据评论中写的错误,这不起作用。

有解决方法吗?我需要一个工厂模式吗?

1 个答案:

答案 0 :(得分:9)

是的,有一个相当简单的方法,至少在这种情况下:创建一个静态方法,为你准备构造函数参数。从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;
}

请注意,它必须是静态的,因为您无法在链式构造函数之前调用this上的任何实例方法。