Java Reference
In-Depth Information
public Die () {}
//automatically created if not present
The constructors inside a class are easily identifiable because they have the same
name as the name of the class and they have no return type (not even void ). They
can be called only through the new keyword (i.e., they cannot be called directly as
other methods). A constructor can be defined as private , but it is usually public .
The job of the constructor is to assign initial values to the instance variables of the
object that is being created.
In our case, the default constructor does not initialize the variable dieValue and there-
fore our initial design of the Die class can be improved. The next version of the class that
includes a proper constructor follows.
class Die {
private int dieValue ;
public Die ()
dieValue = getRandomDieValue() ;
public int getValue () {
if (dieValue > =1 && dieValue < =6) {
return dieValue ;
else {
return 0;
public void rollDie() {
dieValue = getRandomDieValue() ;
private static int getRandomDieValue ()
return ( int )
(Math . random ( )
An example use of the class is shown next.
Die d = new Die () ;
System. out . println (d. getValue () ) ;
for ( int i=0;i
d. rollDie() ;
System. out . println(d. getValue() ) ;
The code creates a new Die object and prints its value. Then it rolls the die one thousand
times and prints the value of the die after every roll. Note that this design shows good
separation of responsibility. The getValue method is only responsible for returning the
value of the die, while the println method does the printing. Combining the two activities
in a single method is an inferior choice because this will reduce the reusability of the method
and make it more prone to errors.
Search WWH ::

Custom Search