Java Reference
In-Depth Information
Exercise 2.39 What about the following version?
System.out.println("# price cents.");
Exercise 2.40 Could either of the previous two versions be used to show the price of tick-
ets in different ticket machines? Explain your answer.
Exercise 2.41 Add a showPrice method to the TicketMachine class. This should have
a void return type and take no parameters. The body of the method should print:
The price of a ticket is xyz cents.
where xyz should be replaced by the value held in the price field when the method is called.
Exercise 2.42 Create two ticket machines with differently priced tickets. Do calls to their
showPrice methods show the same output, or different? How do you explain this effect?
2.10
Method summary
It is worth summarizing a few features of methods at this point, because methods are funda-
mental to the programs we will be writing and exploring in this topic. They implement the
core actions of every object.
A method with parameters will receive data passed to it from the method's caller and will then
use that data to help it perform a particular task. However, not all methods take parameters;
many simply use the data stored in the object's fields to carry out their task.
If a method has a non- void return type, it will return some data to the place it was called from—
and that data will almost certainly be used in the caller for further calculations or program
manipulations. Many methods, though, have a void return type and return nothing, but they
still perform a useful task within the context of their object.
Accessor methods have non- void return types and return information about the object's state.
Mutator methods modify an object's state. Mutators often take parameters whose values are used in
the modification, although it is still possible to write a mutating method that does not take parameters.
2.11
Summary of the naïve ticket machine
We have now examined the internal structure of the naïve ticket machine class in some de-
tail. We have seen that the class has a small outer layer that gives a name to the class, and a
more substantial inner body containing fields, a constructor, and several methods. Fields are
used to store data that enable objects to maintain a state that persists between method calls.
Constructors are used to set up an initial state when an object is created. Having a proper ini-
tial state will enable an object to respond appropriately to method calls immediately following
its creation. Methods implement the defined behavior of the class's objects. Accessor methods
provide information about an object's state, and mutator methods change an object's state.
We have seen that constructors are distinguished from methods by having the same name as
the class in which they are defined. Both constructors and methods may take parameters, but
 
 
Search WWH ::




Custom Search