在java中初始化一个final字段

时间:2014-11-05 15:34:49

标签: java constructor

以下两个java类都初始化了一些最终字段,第一个赢得了编译(变量未初始化错误),第二个编译正常。为什么呢?

public class Craps {
    public static enum Outcome {ONGOING, WIN_FIRST, WIN_POINT, LOSE_FIRST, LOSE_POINT};
    private int currentNumber;
    private final int point;
    private Outcome gameResult = Outcome.ONGOING;
    private static SecureRandom randomNumbers = new SecureRandom();

    public static int rollDice() {
        return 2 + randomNumbers.nextInt(6) + randomNumbers.nextInt(6);
    }

    public Craps() {
        currentNumber = rollDice();
        switch (currentNumber) {
            case 7:case  11:
                gameResult = Outcome.WIN_FIRST;
                break;
            case 2:case 3:case 12:
                gameResult = Outcome.LOSE_FIRST;
                break;
            default:
                point = currentNumber;
        }
    }

    public void moreRolls() {
        currentNumber = rollDice();
        if(currentNumber == point) {
            gameResult = Outcome.WIN_POINT;
        } else if(currentNumber == 7) {
            gameResult = Outcome.LOSE_POINT;
        }
    }


    public Outcome getGameResult() {
        return gameResult;
    }

    public int getPoint() {
        return point;
    }

    public int getCurrentNumber() {
        return currentNumber;
    }
}

public enum Book {
    AHTP("book1", "1998"),
    BHTP("book1", "1998"),
    CHTP("book1", "1998"),
    DHTP("book1", "1998"),
    EHTP("book1", "1998"),
    FHTP("book1", "1998");

    private final String title;
    private final String copyrightYear;

    Book(String bookTitle, String year) {
        title = bookTitle;
        copyrightYear = year;
    }

    public String getCopyrightYear() {
        return copyrightYear;
    }

    public String getTitle() {
        return title;
    }
}

3 个答案:

答案 0 :(得分:3)

必须先使用final变量进行初始化,然后再使用它。在这种情况下

public Craps() {
    currentNumber = rollDice();
    switch (currentNumber) {
        case 7:case  11:
            gameResult = Outcome.WIN_FIRST;
            break;
        case 2:case 3:case 12:
            gameResult = Outcome.LOSE_FIRST;
            break;
        default:
            point = currentNumber;
    }
}

point是一个final变量,不一定要初始化。它仅在currentNumber不等于7,11,2,3或12时初始化。编译器不允许这样做。

答案 1 :(得分:1)

point并不总是设置(对于7,11,2,3,12),在这些情况下你也需要设置点。

答案 2 :(得分:1)

由于point是final,你需要初始化它,即使是7,11,2,3,12的情况。这个中断阻止了初始化。