Java Reference
In-Depth Information
Each of the constructors is used to create a new object. During this creation, the variable
dieValue
is initialized to a random value. Conversely, the
rollDie
method is called after
an object is already created in order to update the existing value of the variable
dieValue
to a random number.
Sometimes, the different constructors of a class have a lot of code in common and it is
tedious to write the same code multiple times. After all, the hallmark of a good program
is that the same code should not repeat. Fortunately, Java provides a mechanism for one
constructor to call a different constructor. In particular, the empty constructor of the
Die
class can be rewritten as follows.
public
Die ()
{
this
(DEFAULT NUMBER OF SIDES) ;
}
The call
this(DEFAULT NUMBER OF SIDES)
means call the constructor of this class that
takes as input a single integer and pass the number
DEFAULT NUMBER OF SIDES
as a param-
eter. Having the empty constructor call other constructors with a default value is a common
trick when writing constructors. Note that the empty constructor cannot directly call the
other constructor by its method name and needs to use the syntax
this(
...
)
.The
this
keyword is used because in Java it means the current object (or the hidden parameter).
The call calls the second constructor and passes the current object as a hidden parameter.
Consider next the new
equals
method of the
Die
class.
public boolean
equals(Die otherDie)
{
return
(
this
. dieValue==otherDie . dieValue) ;
}
If
d1
and
d2
are die objects, then
d1.equals(d2)
will return
true
exactly when the
values of the two dice are the same. The formal parameter
otherDie
corresponds to the
actual parameter
d2
. One can think of the
this
object as being a hidden formal parameter
that corresponds to the actual parameter
d1
. Therefore, the method simply checks if
d1
and
d2
have the same value for the variable
dieValue
. Of course, the reference to the
this
object is unnecessary when there is a single variable
dieValue
that is in scope and the code
can be rewritten as follows.
public boolean
equals(Die otherDie)
{
return
(dieValue==otherDie . dieValue) ;
}
6.7 Array of Objects and Multi-Class Solutions
Now that we are satisfied with the
Die
class, let us examine an implementation of the
DiceCup
class. In the real world, a dice cup will contain a collection of dice. We will model
the real world by creating an array of die objects in the
DiceCup
class.
public class
DiceCup
{
private
Die [ ] dice ;
private int
numberOfDice ;
public static int
DEFAULT NUMBER OF DICE=5 ;
public
DiceCup ()
{
numberOfDice = DEFAULTNUMBER OF DICE ;