Java Reference
In-Depth Information
Return types and return statements work together. The int return type of getPrice is a form
of promise that the body of the method will do something that ultimately results in an integer
value being calculated and returned as the method's result. You might like to think of a method
call as being a form of question to an object and the return value from the method being the
object's answer to that question. In this case, when the getPrice method is called on a ticket
machine, the question is, What do tickets cost? A ticket machine does not need to perform any
calculations to be able to answer that, because it keeps the answer in its price field. So the
method answers by just returning the value of that variable. As we gradually develop more-
complex classes, we shall inevitably encounter more-complex questions that require more work
to supply their answers.
Accessor and mutator methods
We often describe methods such as the two “get” methods of TicketMachine ( getPrice
and getBalance ) as accessor methods (or just accessors ). This is because they return in-
formation to the caller about the state of an object; they provide access to information about
the object's state. An accessor usually contains a return statement in order to pass back that
Accessor meth-
ods return informa-
tion about the state
of an object.
There is often confusion about what “returning a value” actually means in practice. People
often think it means that something is printed by the program. This is not the case at all—
we shall see how printing is done when we look at the printTicket method. Rather,
returning a value means that some information is passed internally between two different
parts of the program. One part of the program has requested information from an object via
a method call, and the return value is the way the object has of passing that information
back to the caller.
Exercise 2.23 Compare the header and body of the getBalance method with the header
and body of the getPrice method. What are the differences between them?
Exercise 2.24 If a call to getPrice can be characterized as “What do tickets cost?” how
would you characterize a call to getBalance ?
Exercise 2.25 If the name of getBalance is changed to getAmount , does the return
statement in the body of the method also need to be changed for the code to compile? Try it
out within BlueJ. What does this tell you about the name of an accessor method and the name
of the field associated with it?
Exercise 2.26 Write an accessor method getTotal in the TicketMachine class. The
new method should return the value of the total field.
Exercise 2.27 Try removing the return statement from the body of getPrice . What error
message do you see now when you try compiling the class?
Search WWH ::

Custom Search