qed
qed

Reputation: 23154

Initialize a final field in java

The following two java classes both initilize some final fields, the first won't compile (variable not initilized error), the second compiles fine. Why?

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;
    }
}

Upvotes: 0

Views: 84

Answers (3)

Sualeh Fatehi
Sualeh Fatehi

Reputation: 4784

Since point is final, you need to initialize it even for case 7, 11, 2, 3, 12. The break is preventing initialization.

Upvotes: 1

flob
flob

Reputation: 3908

pointis not always set (for 7, 11, 2, 3, 12), you will need to set point in those cases too.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280171

A final variable must be initialized before you ever use it. In this case

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, which is a final variable, is not necessarily initialized. It's only initialized if currentNumber doesn't equal 7, 11, 2, 3, or 12. The compiler will not allow this.

Upvotes: 3

Related Questions