Java Reference
In-Depth Information
Instance Methods
Just as declaring variables did not fully instantiate the external class, Rooms,
constructing an instance by itself does not provide a means to enter data into
that instance — for that, you need an instance method. An instance method
operates or manipulates variables for an external class. While external classes use
constructor methods to allow driver classes to instantiate them, external classes
use instance methods to allow driver classes to manipulate the object's data. The
variables manipulated within an instance method, which are local in scope, are
called instance variables . When called by the driver class, instance methods
must use the class.method() notation, in which class is the name of the external
class object.
Java programmers typically use a user-friendly, active verb in the name of
the instance methods. For example, an instance method to retrieve data about
an invoice might be named getBalance(). An instance method to assign a new
balance might be named setBalance(). While other data members are declared
private so that the driver class does not change the values, the get() and set()
instance methods usually are declared public so that data used in the methods
may be validated.
Naming Instance Methods
When naming an instance method, use a user-friendly, active
verb in the name. For example, methods that retrieve and
assign data commonly are named with the verbs, get and set.
A method to retrieve data about an invoice thus might be
named getBalance(). The method to assign a new balance
might be named setBalance().
The bookRoom() Method
The Rooms class needs an instance method to book a specific room.
Figure 5-15 shows the code for the instance method named bookRoom(),
a name that describes the purpose of the instance method. Line 30 sets the
bookRoom() method to have public access, thus allowing its use in other pro-
grams. The bookRoom() method accepts a passed parameter, which is a boolean
value representing whether or not the user has requested a smoking room. The
bookRoom() method returns an int value to the driver class, representing the
number of the booked room (or the value, zero, if no rooms are available).
Search WWH ::




Custom Search