Java Reference
In-Depth Information
Exercise 2.60 What is wrong with the following version of the constructor of TicketMachine ?
public TicketMachine(int cost)
int price = cost;
balance = 0;
total = 0;
Try out this version in the better-ticket-machine project. Does this version compile? Create
an object and then inspect its fields. Do you notice something wrong about the value of the
price field in the inspector with this version? Can you explain why this is?
It is quite common to initialize local variables within their declaration. So we could abbrevi-
ate the first two statements of refundBalance as
int amountToRefund = balance;
but it is still important to keep in mind that there are two steps going on here: declaring the
variable amountToRefund and giving it an initial value.
Pitfall A local variable of the same name as a field will prevent the field being accessed from within
a constructor or method. See Section 3.12.2 for a way around this when necessary.
Fields, parameters, and local variables
With the introduction of amountToRefund in the refundBalance method, we have now
seen three different kinds of variables: fields, formal parameters, and local variables. It is
important to understand the similarities and differences between these three kinds. Here is a
summary of their features:
All three kinds of variables are able to store a value that is appropriate to their defined types.
For instance, a defined type of int allows a variable to store an integer value.
Fields are defined outside constructors and methods.
Fields are used to store data that persist throughout the life of an object. As such, they main-
tain the current state of an object. They have a lifetime that lasts as long as their object lasts.
Fields have class scope: their accessibility extends throughout the whole class, so they can be
used within any of the constructors or methods of the class in which they are defined.
As long as they are defined as private , fields cannot be accessed from anywhere outside
their defining class.
Formal parameters and local variables persist only for the period that a constructor or method
executes. Their lifetime is only as long as a single call, so their values are lost between calls.
As such, they act as temporary rather than permanent storage locations.
Search WWH ::

Custom Search