Monday 15 August 2011

constructor - Initialize a final field in java -



constructor - Initialize a final field in java -

the next 2 java classes both initilize final fields, first won't compile (variable not initilized error), sec 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() { homecoming 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() { homecoming gameresult; } public int getpoint() { homecoming point; } public int getcurrentnumber() { homecoming 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() { homecoming copyrightyear; } public string gettitle() { homecoming title; } }

a final variable must initialized before ever utilize it. in 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, final variable, not initialized. it's initialized if currentnumber doesn't equal 7, 11, 2, 3, or 12. compiler not allow this.

java constructor

No comments:

Post a Comment