Scope – methods and variables
If you declare a variable in a method, whether that is one of the Android methods such as onCreate
or one of our own methods, it can only be used within that method.
It is no use doing this in the onCreate
method:
int a = 0;
And then after, trying to do this in the newGame
method or some other method:
a++;
We will get an error because a
is only visible in the method it was declared in. At first, this might seem like a problem but perhaps surprisingly, it is actually very useful.
That is why we declared those variables outside of all the methods, just after the class declaration. Here they are again, as a reminder:
public class SubHunter extends Activity {     // These variables can be "seen"     // throughout the SubHunter class     int numberHorizontalPixels;     int numberVerticalPixels;     int blockSize;  &...