Java Reference
In-Depth Information
fields. It will be possible with some fields, such as balance and total , to set sensible initial
values by assigning a constant number - zero in this case. With others, such as the ticket price,
it is not that simple, as we do not know the price that tickets from a particular machine will have
until that machine is constructed. Recall that we might wish to create multiple machine objects to
sell tickets with different prices, so no one initial price will always be right. You will know from
experimenting with creating TicketMachine objects within BlueJ that you had to supply the cost
of the tickets whenever you created a new ticket machine. An important point to note here is that
the price of a ticket is initially determined externally and then has to be passed into the constructor.
Within BlueJ you decide the value and enter it into a dialog box. Part of the task of the constructor
is to receive that value and store it in the price field of the newly created ticket machine so that the
machine can remember what that value was without you having to keep reminding it.
We can see from this that one of the most important roles of a field is to remember external in-
formation passed into the object so that that information is available to an object throughout its
lifetime. Fields, therefore, provide a place to store long-lasting (i.e., persistent) data.
Figure 2.3 shows a ticket-machine object after the constructor has executed. Values have now
been assigned to the fields. From this diagram, we can tell that the ticket machine was created
by passing in 500 as the value for the ticket price.
Figure 2.3
A TicketMachine
object after initialization
(created for 500-cent
In the next section, we discuss how values are received by an object from outside.
Note In Java, all fields are automatically initialized to a default value if they are not explicitly initialized.
For integer fields, this default value is zero. So, strictly speaking, we could have done without setting
balance and total to zero, relying on the default value to give us the same result. However, we prefer to
write the explicit assignments anyway. There is no disadvantage to it, and it serves well to document
what is actually happening. We do not rely on a reader of the class knowing what the default value is,
and we document that we really want this value to be zero and have not just forgotten to initialize it.
Parameters: receiving data
Constructors and methods play quite different roles in the life of an object, but the way in
which both receive values from outside is the same: via parameters. You may recall that we
briefly encountered parameters in Chapter 1 (Section 1.4). Parameters are another sort of
Search WWH ::

Custom Search