Java Reference
In-Depth Information
int size, weight;
char category;
double value, cost;
Data
declarations
Method
declarations
FIGURE 4.2
The members of a class: data and method declarations
The
Die
class is shown in Listing 4.2. It contains two data values: an integer
constant (
MAX
) that represents the maximum face value of the die, and an inte-
ger variable (
faceValue
) that represents the current face value of the die. It also
contains a constructor called
Die
and four regular methods:
roll
,
setFaceValue
,
getFaceValue
, and
toString.
You will recall from Chapters 2 and 3 that constructors are special methods
that have the same name as the class. The
Die
constructor gets called when the
new
operator is used to create a new instance of the
Die
class. The rest of the
methods in the
Die
class define the various services provided by
Die
objects.
We use a header block of documentation to explain the purpose of each
method in the class. This practice is not only crucial for anyone trying to under-
stand the software, it also separates the code visually so that it's easy for the eye
to jump from one method to the next while reading the code.
Figure 4.3 lists the methods of the
Die
class. From this point of view, it looks
no different from any other class that we've used in previous examples. The only
important difference is that the
Die
class was not provided for us by the Java
standard class library. We wrote it ourselves.
The methods of the
Die
class include the ability to roll the die, producing a
new random face value. The
roll
method returns the new face value to the call-
ing method, but you can also get the current face value at any time using the
getFaceValue
method. The
setFaceValue
method sets the face value explicitly,
as if you had reached over and turned the die to whatever face you wanted. The
toString
method of any object gets called automatically whenever you pass the
object to a
print
or
println
method to obtain a string description of the object
VideoNote
Dissecting the
Die
class.
Search WWH ::
Custom Search