Java Reference
In-Depth Information
is mostly a question of preference. Our style is not necessarily better than all others. However,
it is important to choose one style and then use it consistently, because then your classes will be
easier to read and understand.
Code 2.2
Our ordering of fields,
constructors, and
public class ClassName
Exercise 2.10 From your earlier experimentation with the ticket machine objects within BlueJ,
you can probably remember the names of some of the methods- printTicket , for instance.
Look at the class definition in Code 2.1 and use this knowledge, along with the additional infor-
mation about ordering we have given you, to make a list of the names of the fields, constructors,
and methods in the TicketMachine class. Hint: There is only one constructor in the class.
Exercise 2.11 What are the two features of the constructor that make it look significantly
different from the methods of the class?
Fields store data persistently within an object. The TicketMachine class has three fields:
price , balance , and total . Fields are also known as instance variables, because the word
variable is used as a general term for things that store data in a program. We have defined
the fields right at the start of the class definition (Code 2.3). All of these variables are asso-
ciated with monetary items that a ticket-machine object has to deal with:
Fields store data
for an object to
use. Fields are also
known as instance
price stores the fixed price of a ticket;
balance stores the amount of money inserted into the machine by a user prior to asking for
a ticket to be printed;
total stores the total amount of money inserted into the machine by all users since the ma-
chine object was constructed (excluding any current balance). The idea is that, when a ticket
is printed, any money in the balance is transferred to the total.
Code 2.3
The fields of the
public class TicketMachine
private int price;
private int balance;
private int total;
Constructor and methods omitted.
Search WWH ::

Custom Search