Java Reference
In-Depth Information
Exercise 2.28 Compare the method headers of getPrice and printTicket in
Code 2.1. Apart from their names, what is the main difference between them?
Exercise 2.29 Do the insertMoney and printTicket methods have return state-
ments? Why do you think this might be? Do you notice anything about their headers that might
suggest why they do not require return statements?
The get methods of a ticket machine perform similar tasks: returning the value of one of their
object's fields. The remaining methods— insertMoney and printTicket —have a much
more significant role, primarily because they change the value of one or more fields of a ticket-
machine object each time they are called. We call methods that change the state of their object
mutator methods (or just mutators ).
Concept:
Mutator methods
change the state of
an object.
In the same way as we think of a call to an accessor as a request for information (a question), we
can think of a call to a mutator as a request for an object to change its state. The most basic form
of mutator is one that takes a single parameter whose value is used to directly overwrite what
is stored in one of an object's fields. In a direct complement to “get” methods, these are often
called “set” methods, although the TicketMachine does not have any of those, at this stage.
One distinguishing effect of a mutator is that an object will often exhibit slightly different
behavior before and after it is called. We can illustrate this with the following exercise.
Exercise 2.30 Create a ticket machine with a ticket price of your choosing. Before doing
anything else, call the getBalance method on it. Now call the insertMoney method
(Code 2.6) and give a non-zero positive amount of money as the actual parameter. Now
call getBalance again. The two calls to getBalance should show different outputs,
because the call to insertMoney had the effect of changing the machine's state via its
balance field.
The header of insertMoney has a void return type and a single formal parameter,
amount , of type int . A void return type means that the method does not return any value
to its caller. This is significantly different from all other return types. Within BlueJ, the dif-
ference is most noticeable in that no return-value dialog is shown following a call to a void
Code 2.6
The insertMoney
method
/**
* Receive an amount of money in cents from a customer.
*/
public void insertMoney( int amount)
{
balance = balance + amount;
}
 
Search WWH ::




Custom Search