Java Reference
In-Depth Information
The Rooms() Constructor Method
In this project, the Rooms() constructor method , which creates a
working instance of the Rooms object by defining the components, becomes
a constructor for use by driver classes.
Figure 5-11 lists the code for a Rooms() constructor method header within
the Rooms class. As shown in line 19, the Rooms() constructor method begins
with an access modifier, public, followed by the name of the method. Recall that
a constructor method name must match the name of the class object. Just as the
Label() method helped construct a Label object in previous programs, the
Rooms() method will construct a Rooms object when called by the driver class,
Reservations. The constructor method header in line 19 returns an initialized
Rooms object. The constructor method header includes two parameters, which
are passed to the Rooms() constructor method from the driver class arguments.
The parameters represent two integer values: the number of nonsmoking and
smoking rooms to be created.
Naming Instance Variables
Identifier names in driver classes typically use full words to
represent variables, such as nonsmoking and smoking. When
naming instance variables, however, it is common practice to use
shortened names such as non and sm for parameters.
19
public Rooms ( int non, int sm )
20
{
21
//construct an array of boolean values equal to the total number of rooms
22
occupied = new boolean [ sm+non ] ;
FIGURE 5-11
Line 22 constructs the array named occupied. The occupied array contains
boolean values and has the same number of elements as there are total rooms —
the smoking and nonsmoking values from line 19 added together. For example,
if the Reservations driver class calls for a set of rooms with nine nonsmoking
rooms and five smoking rooms, the Rooms() constructor method will create an
array with a length of 14 (that is, 9 + 5).
Search WWH ::




Custom Search