Java Reference
In-Depth Information
private int getRandomDieValue ()
{
return ( int )
(Math . random ( )
numberOfSides + 1) ;
}
public String toString() {
return dieValue+ "" ;
}
public boolean equals(Die otherDie) {
return (dieValue==otherDie . dieValue) ;
}
}
The above class is well designed. Every method does a single operation. The methods
are built around the data item dieValue .
6.5 Instance versus Static
Let us carefully examine the changes to the code. We introduced a variable DE-
FAULT NUMBER OF SIDES, which stores the default number of sides for a die. This
variable is not subject to change (i.e., it is a constant) and therefore it is defined using
the final keyword. It is safe to define a constant as public because its value cannot be
changed. If someone wants to see the default number of sides for a die, then they can refer
to the variable Die.DEFAULT NUMBER OF SIDES . Note that the variable is defined as static ,
which means that it belongs to the class and not to a particular instance of the class. This
is the reason that it is accessed by specifying the name of the class and not the name of
an instance of the class. The variable is static because the default number of sides will be
the same for every die that is created.
Figure 6.3 shows a pictorial representation of the Die class. In the example, three ob-
jects are created. Since the variable dieValue is instance, every object of type Die has a
unique copy of this variable. As the figure suggests, we can have three different values for
the variable dieValue - one value for every object. Conversely, we have a single variable
DEFAULT NUMBER OF SIDES . We could have 0 dice or 100 dice. The default number of sides
will still be equal to 6.
Note that we have made the getRandomDieValue method an instance method by remov-
ing the static keyword. The reason is that it needs access to the variable numberOfSides .
However, this new variable is an instance variable (i.e., every die can have a different value
for this variable). Therefore, the method also needs to become instance (i.e., it matters
which die it is invoked on). Note that as Table 6.1 suggests a static method cannot access
instance variables. The new design allows us to have different dice with a different number
of sides. Maybe this is stupid for the Yahtzee game. However, it will allow us to easily
extend the game if we want to introduce one ten-sided die as part of the game.
Search WWH ::




Custom Search