Scope and variables revisited
You might remember in the Real World Methods
project the slightly disturbing anomaly was that variables in one method were not apparently the same as those from another even if they do have the same name. If you declare a variable in a method, whether that is one of the life cycle methods or one of our own methods, it can only be used within that method.
It is no use if we do this in onCreate
:
int a = 0;
And then, following that, we try to do this in onPause
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 surprisingly, it is actually an especially useful feature of Java.
I have already mentioned that the term used to describe this is scope. A variable is said to be in scope when it is usable and out of scope when it is not. The topic of scope is best discussed along with classes, and we will do so in Chapter 10, Object-Oriented...