Java Reference
In-Depth Information
A default empty constructor is only created if no explicit constructors are cre-
ated. Therefore, if you create any constructor, you should consider creating an empty
constructor. If you do not do so, then existing code that relies on the default empty
constructor will no longer compile.
The empty constructor contains the following code.
public
Die ()
{
numberOfSides = DEFAULTNUMBER OF SIDES ;
dieValue = getRandomDieValue() ;
}
The first line sets the number of sides of the die to the default number. The sec-
ond line sets the value of the die to a random value. Note that the
getRandomDieValue
method was changed to generate a random number between 1 and the value for the variable
numberOfSides
. Note as well that the constructor sets the value of both instance variables.
This is not accidental.
A constructor is called when an object is being created. Initially, the value of
all the instance variables of the object are undefined. Therefore, it is the job of the
constructor to give value to these variables. If the value of a variable is not specified
as input to the constructor, then a default value or a random value can be used to
initialize the instance variable.
In our case, the empty constructor gives no information about the value of the two
variables. Therefore, we set the variable
numberOfSides
to the default value and the variable
dieValue
to a random number.
The second constructor has the following code.
public
Die(
int
numberOfSides)
{
this
. numberOfSides = numberOfSides ;
dieValue = getRandomDieValue() ;
}
The first line sets the number of sides of the die to the value of the input parameter.
Note that in this method there are two variables
numberOfSides
: the input variable to the
method (i.e., the formal parameter) and the instance variable of the class. When we refer to
the variable
numberOfSides
, we are referring to the variable that is defined in the innermost
scope, which will be the input parameter to the method. If we want to refer to the instance
variable
numberOfSides
, then we need to write
this.numberOfSides
.The
this
object is
the hidden parameter on which the method is called. For constructors, it is the object that
is being created. Therefore, when we write:
this.numberOfSides
, we actually mean the
variable
numberOfSides
of the current object. The second line of the method sets the value
of the other instance variable of the
Die
class. Note that the second line of the method can
also be rewritten as follows.
this
. dieValue = getRandomDieValue () ;
However, since there is a single variable
dieValue
that is visible inside the method, the
extra indirection is unnecessary.
Note that the two constructors of the
Die
class are similar to the
rollDie
method. All
methods change the variable
dieValue
to a random number. Note that even if the
rollDie
method had the same code as a constructor, the two methods are not interchangeable.