Java Reference
In-Depth Information
the
balance
field. It is common to have fields whose values change often, such as
balance
and
total
, and others that change rarely or not at all, such as
price
. The fact that the value of
price
doesn't vary once set doesn't alter the fact that it is still called a variable. In the follow-
ing sections, we shall also meet other kinds of variables in addition to fields, but they will all
share the same fundamental purpose of storing data.
The
price
,
balance
, and
total
fields are all the data items that a ticket-machine object needs
to fulfill its role of receiving money from a customer, printing tickets, and keeping a running
total of all the money that has been put into it. In the following sections, we shall see how the
constructor and methods use those fields to implement the behavior of naïve ticket machines.
Exercise 2.12
What do you think is the
type
of each of the following fields?
private int count;
private Student representative;
private Server host;
Exercise 2.13
What are the
names
of the following fields?
private boolean alive;
private Person tutor;
private Game game;
Exercise 2.14
From what you know about the naming conventions for classes, which of the
type names in Exercises 2.12 and 2.13 would you say are class names?
Exercise 2.15
In the following field declaration from the
TicketMachine
class
private int price;
does it matter which order the three words appear in? Edit the
TicketMachine
class to
try different orderings. After each change, close the editor. Does the appearance of the class
diagram after each change give you a clue as to whether or not other orderings are possible?
Check by pressing the
Compile
button to see if there is an error message.
Make sure that you reinstate the original version after your experiments!
Exercise 2.16
Is it always necessary to have a semicolon at the end of a field declaration?
Once again, experiment via the editor. The rule you will learn here is an important one, so be
sure to remember it.
Exercise 2.17
Write in full the declaration for a field of type
int
whose name is
status
.
From the definitions of fields we have seen so far, we can begin to put a pattern together that
will apply whenever we define a field variable in a class:
■
They usually start with the reserved word
private
.
■
They include a type name (such as
int
,
String
,
Person
, etc.)
Search WWH ::
Custom Search