Scope: Methods and Variables
If you declare a variable in a method, whether that is one of the Android methods like onCreate
or one of our own methods it can only be used within that method.
It is no use doing this in onCreate
:
int a = 0;
And, then trying to do this in newGame
or some other method:
a++;
We will get an error because a
is only visible within the method it was declared. 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; … …
When we do it as we did in the previous code the variables can be used throughout the code file. As this and other projects progress we will declare some variables...