- Android Programming for Beginners
- John Horton
- 361字
- 2021-07-23 14:47:09
Scope and variables revisited
You might remember that 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 did have the same name. If you declare a variable in a method, whether that is one of the lifecycle methods 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 onPause
or some other method:
a++;
We will get an error because a
is only visible within the method it was declared in. At first, this might seem like a problem, but perhaps surprisingly, it is actually a very useful feature of Java.
The term used to describe this is "scope". A variable is said to be in a scope when it is usable and out of the scope when it is not. The topic of scope is best discussed along with classes, and we will in the next chapter, but as a sneak look at what lies ahead you might like to know that a class can have its very own variables, and when it does, they have a scope for the whole class. That is, all its methods can see and use them. We call them member variables or fields.
To declare a member variable, you can simply use the usual syntax after the start of the class, outside of any method declared in the class. If our app started like this:
public class MainActivity extends AppCompatActivity { int mSomeVariable = 0; // Rest of code and methods follow as usual // …
We could use mSomeVariable
anywhere, inside any method in this class. Our new variable, mSomeVariable
, has class scope. We append m
to the variable name simply to remind us when we see it that it is a member variable. This is not required, but it is a useful convention.
Here are a couple of hypothetical method questions to try and make some of what we have learned stick a little more. Try and answer them yourself.
- 精通Nginx(第2版)
- Objective-C Memory Management Essentials
- Interactive Data Visualization with Python
- PowerCLI Cookbook
- Arduino開發(fā)實戰(zhàn)指南:LabVIEW卷
- 軟件測試項目實戰(zhàn)之性能測試篇
- 21天學(xué)通C++(第6版)
- Mathematica Data Analysis
- 劍指MySQL:架構(gòu)、調(diào)優(yōu)與運維
- 微信小程序全棧開發(fā)技術(shù)與實戰(zhàn)(微課版)
- Kotlin極簡教程
- 寫給大家看的Midjourney設(shè)計書
- Mastering VMware Horizon 7(Second Edition)
- 3D Printing Designs:The Sun Puzzle
- Building UIs with Wijmo