Java Reference
In-Depth Information
Formal parameters are defined in the header of a constructor or method. They receive their
values from outside, being initialized by the actual parameter values that form part of the
constructor or method call.
Formal parameters have a scope that is limited to their defining constructor or method.
Local variables are defined inside the body of a constructor or method. They can be initial-
ized and used only within the body of their defining constructor or method. Local variables
must be initialized before they are used in an expression—they are not given a default value.
Local variables have a scope that is limited to the block in which they are defined. They are
not accessible from anywhere outside that block.
Exercise 2.61 Add a new method, emptyMachine , that is designed to simulate emptying
the machine of money. It should reset total to be zero but also return the value that was
stored in total before it was reset.
Exercise 2.62 Rewrite the printTicket method so that it declares a local vari-
able, amountLeftToPay . This should then be initialized to contain the difference between
price and balance . Rewrite the test in the conditional statement to check the value of
amountLeftToPay . If its value is less than or equal to zero, a ticket should be printed; other-
wise, an error message should be printed stating the amount left to pay. Test your version to
ensure that it behaves in exactly the same way as the original version. Make sure that you call
the method more than once, when the machine is in different states, so that both parts of the
conditional statement will be executed on separate occasions.
Exercise 2.63 Challenge exercise Suppose we wished a single TicketMachine object
to be able to issue tickets of different prices. For instance, users might press a button on the
physical machine to select a discounted ticket price. What further methods and/or fields would
need to be added to TicketMachine to allow this kind of functionality? Do you think that
many of the existing methods would need to be changed as well?
Save the better-ticket-machine project under a new name, and implement your changes in the
new project.
Summary of the better ticket machine
In developing a better version of the TicketMachine class, we have been able to address
the major inadequacies of the naïve version. In doing so, we have introduced two new lan-
guage constructs: the conditional statement and local variables.
A conditional statement gives us a means to perform a test and then, on the basis of the result
of that test, perform one or the other of two distinct actions.
Local variables allow us to calculate and store temporary values within a constructor or
method. They contribute to the behavior that their defining method implements, but their
values are lost once that constructor or method finishes its execution.
Search WWH ::

Custom Search