Java Reference
In-Depth Information
harrysChecking.deposit(500);
then a parameter variable called amount is created and initialized with the parameter
value, 500. When the method returns, the amount variable dies. The same holds for
the local variable newBalance . When the deposit method reaches the line
double newBalance = balance + amount;
the variable comes to life and is initialized with the sum of the object's balance and
the deposit amount. The lifetime of that variable extends to the end of the method.
However, the deposit method has a lasting effect. Its next line,
balance = newBalance;
sets the balance instance field, and that field lives beyond the end of the deposit
method, as long as the BankAccount object is in use.
The second major difference between instance fields and local variables is
initialization. You must initialize all local variables. If you don't initialize a local
variable, the compiler complains when you try to use it.
Instance fields are initialized to a default value, but you must initialize local
variables.
Parameter variables are initialized with the values that are supplied in the method call.
Instance fields are initialized with a default value if you don't explicitly set them in a
constructor. Instance fields that are numbers are initialized to 0. Object references are
set to a special value called null . If an object reference is null , then it refers to no
object at all. We will discuss the null value in greater detail in Section 5.2.5 .
Inadvertent initialization with 0 or null is a common cause of errors. Therefore, it is
a matter of good style to initialize every instance field explicitly in every constructor.
S ELF C HECK
13. What do local variables and parameter variables have in common? In
which essential aspect do they differ?
Search WWH ::




Custom Search