Java Reference
In-Depth Information
What sort of variable is amountToRefund ? We know that it is not a field, because fields are
defined outside methods. It is also not a parameter, as those are always defined in the method
header. The amountToRefund variable is what is known as a local variable, because it is de-
fined inside a method body.
Local variable declarations look similar to field declarations, but they never have private or
public as part of them. Constructors can also have local variables. Like formal parameters, lo-
cal variables have a scope that is limited to the statements of the method to which they belong.
Their lifetime is the time of the method execution: they are created when a method is called and
destroyed when a method finishes.
You might wonder why there is a need for local variables if we have fields. Local variables
are primarily used as temporary storage, to help a single method complete its task; we think of
them as data storage for a single method. In contrast, fields are used to store data that persists
through the life of a whole object. The data stored in fields is accessible to all of the object's
methods. We try to avoid declaring as fields variables that really only have a local (method-
level) usage, whose values don't have to be retained beyond a single method call. So even if
two or more methods in the same class used local variables for a similar purpose, it would not
be appropriate to define them as fields if their values don't need to persist beyond the end of
the methods.
In the refundBalance method, amountToRefund is used briefly to hold the value of the
balance immediately prior to the latter being set to zero. The method then returns the remem-
bered value of the balance. The following exercises will help to illustrate why a local variable is
needed here, as we try to write the refundBalance method without one.
Exercise 2.58 Why does the following version of refundBalance not give the same re-
sults as the original?
public int refundBalance()
balance = 0;
return balance;
What tests can you run to demonstrate that it does not?
Exercise 2.59 What happens if you try to compile the TicketMachine class with the fol-
lowing version of refundBalance ?
public int refundBalance()
return balance;
balance = 0;
What do you know about return statements that helps to explain why this version does not
Search WWH ::

Custom Search