Java Reference
In-Depth Information
6.4 The
toString
Method
It seems tedious to write
System.out.println(d.getValue())
every time we want to
print the value of the die
d
. Can we just write
System.out.println(d)
and expect Java to
automatically convert the die
d
to a string? Surprisingly, the answer is yes. The
toString
method is defined for every Java object. For example, we can always send an object to the
print
and
println
methods. The object is automatically converted to a string by calling
the
toString
method.
The default implementation of the
toString
method does not do much: it just returns
the name of the class and the address (or the reference, to be more precise) of the object
(we saw this behavior when we tried to print an array). To demonstrate this behavior again,
let us rewrite our code as follows.
Die d =
new
Die () ;
System. out . println (d) ;
for
(
int
i=0;i
<
1000;
i++)
{
d. rollDie() ;
System. out . println (d) ;
}
One possible output is:
Die@42e816
one thousand and one times. In order to get mean-
ingful output, we need to add the
toString
method to the
Die
class. One possible imple-
mentation follows.
public
String toString()
{
return
dieValue+
""
;
}
Note that the
Die
class contains the value of the die as an integer. We can use the
trick of adding an integer and an empty string to convert the integer to a string. We will
make one more modification to the
Die
class and make the number of sides on the die a
parameter. Note that the above
toString
method actually overrides an existing
toString
method. Therefore, if we want the printing of a die to work properly, we cannot change the
name of the
toString
method or its return value type. Note that the
toString
method
does not print anything. It simply converts an object to a string.
class
Die
{
public static final int
DEFAULT NUMBER OF SIDES=6 ;
private int
dieValue ;
private int
numberOfSides ;
public
Die ()
{
numberOfSides = DEFAULTNUMBER OF SIDES ;
dieValue = getRandomDieValue() ;
}
public
Die(
int
numberOfSides)
{
this
. numberOfSides = numberOfSides ;
dieValue = getRandomDieValue() ;
}
public void
rollDie()
{
dieValue = getRandomDieValue() ;
}