Displaced Hoser Displaced Hoser - 1 month ago 12
Android Question

Java overriding method does not recognize variable defined in super

Finding a strange error with inheritance in Java (for Android) - I'm sure I'm doing something wrong but not sure what. My class SimonActivity extends GameActivity.

Within GameActivity there is this method that sets the values of a Map called gameVars:

protected void setGameOptions(Bundle extras)
{
Map<String, Integer> gameVars = new HashMap<String, Integer>();

String difficulty = extras.getString(DIFFICULTY);

for (TuningVariable t:tuningVars)
{
...
gameVars.put(t.name, varValue);
}
}


Now I try to override this in SimonActivity as follows:

protected void setGameOptions(Bundle extras)
{
super.setGameOptions(extras);

winPoints = gameVars.get("winPoints");
successBump = gameVars.get("successBump");
}


But when I compile, SimonActivity gives me the error "cannot find symbol variable gameVars"; the instances of gameVars in SimonActivity show up in red in Android Studio; and in GameActivity, Studio tells me that the contents of gameVars are updated, but never queried.

Obviously the overriding method in the SimonActivity subclass is not recognizing the gameVars variable from the GameActivity superclass even though I have run super. Why not? What should I change?

(I tried changing the calls in SimonActivity from gameVars to super.gameVars but that didn't make a difference.)

Answer

You should declare gameVars as a member of your GameActivity. You're declaring it inside the method call so they will be deleted as soon as your method returns. Also as far as I know an overriding method could not access a local member of the overridden method.