Java Reference
In-Depth Information
Fields are small amounts of space inside an object that can be used to store data persis-
tently. Every object will have space for each field declared in its class. Figure 2.2 shows a
diagrammatic representation of a ticket-machine object with its three fields. The fields have
not yet been assigned any values; once they have, we can write each value into the box rep-
resenting the field. The notation is similar to that used in BlueJ to show objects on the object
bench, except that we show a bit more detail here. In BlueJ, for space reasons, the fields
are not displayed on the object icon. We can, however, see them by opening an inspector
window (Section 1.5).
Figure 2.2
An object of class
TicketMachine
WLFNHW0DFKLQH
7LFNHW0DFKLQH
SULFH
EDODQFH
WRWDO
Each field has its own declaration in the source code. On the line above each in the full class
definition, we have added a single line of text—a comment —for the benefit of human readers
of the class definition:
Concept:
Comments are
inserted into the
source code of a
class to provide
explanations to
human readers.
They have no effect
on the functionality
of the class.
// The price of a ticket from this machine.
private int price;
A single-line comment is introduced by the two characters “//”, which are written with no
spaces between them. More-detailed comments, often spanning several lines, are usually writ-
ten in the form of multiline comments. These start with the character pair “/*” and end with the
pair “*/”. There is a good example preceding the header of the class in Code 2.1.
The definitions of the three fields are quite similar:
All definitions indicate that they are private fields of the object; we shall have more to say
about what this means in Chapter 5, but for the time being we will simply say that we always
define fields to be private.
All three fields are of type int - int is another keyword and represents the data type in-
teger. This indicates that each can store a single whole-number value, which is reasonable
given that we wish them to store numbers that represent amounts of money in cents.
It is because fields can store values that can vary over time that they are also known as vari-
ables . The value stored in a field can be changed from its initial value if required. For instance,
as more money is inserted into a ticket machine, we shall want to change the value stored in
 
Search WWH ::




Custom Search