Java Reference
In-Depth Information
dieValue = 3
dieValue =4
numberOfSides = 6
numberOfSides = 6
DEFAULT_NUMBER_OF_SIDES = 6
dieValue = 5
numberOfSides=5
class Die
FIGURE 6.3:
The
Die
class.
Good software practices suggest that we write code that is easily extendable. How-
ever, we should only do that when the complexity of the code is not negatively affected.
For example, it may not be worth adding 1000 lines of code in order to make the code
friendly toward a future feature that will probably be never implemented. However, if
only 10 lines are needed to make the code new-feature-friendly, then the extra effort
may be well worth it. The good programmer knows how to strike a balance between
making the code expendable and keeping it simple.
Note that a
static
method is invoked on a class and not an object. Therefore, if
the
getRandomDieValue
method was
static
, then we could not refer to the variable
numberOfSides
in it. The reason is that there are three objects inside the
Die
class and
every object can have a different value for the variable
numberOfSides
. Another way to
think about it is that every instance method has an access to a hidden parameter: the ob-
ject on which the method is called. The hidden parameter will tell the
getRandomDieValue
method which one of the three variables
numberOfSides
should be used.
6.6 Non-empty Constructors and the Hidden Parameter
this
Two constructors are added to the
Die
class: an empty constructor and a constructor
that takes as input the number of sides. A default empty constructor is only created if no
constructors are present in the class. In other words, if the empty constructor is missing
from the
Die
class code, then a default empty constructor that does nothing will not be
generated.