public class GameManager {
private static GameManager INSTANCE;
private final int INITIAL_SCORE = 0;
private int mCurrentScore;
GameManager(){
}
public static GameManager getInstance(){
if(INSTANCE == null){
INSTANCE = new GameManager();
}
return INSTANCE;
}
public int getCurrentScore(){
return mCurrentScore;
}
public void incrementScore(int pIncrementBy){
mCurrentScore += pIncrementBy;
}
public void resetGame(){
mCurrentScore = GameManager.INITIAL_SCORE;
}
}
I run the above code in eclipse.
I’d like to know why eclipse told me “Cannot make a static reference to the non-static field GameManager.INITIAL_SCORE” when assigning the value of GameManager.INITIAL_SCORE to that of mCurrentScore. mCurrentScore is not static, is it? If mCurrentScore is not static, why should I declare INITIAL_SCORE as static?
When you prefix a variable with a class name you are telling Java the variable is static. Since the variable is not static it is giving you an error. The code should read: