Java Reference
In-Depth Information
However, now the mapping that the penny is 1 cent, the nickel is 5 cents, the dime is 10
cents, and the quarter is 25 cents is missing.
Suppose that we have a reference to a variable value of type Currency .Ifwewantto
access the text that is associated with the coin (e.g., PENNY), then we can just call the
toString method on the value object. Note that in our example, the toString method
is automatically called on the variable value . In other words, Java actually executed the
following code.
public String toString() {
return value . toString()+ " that is " +face . toString() ;
Thereasonisthatthe toString method is automatically called when the concatenation
operator “+” is used and an object is specified. This implies that a variable of an enum type
is treated in Java similar to an object variable. Note that there is no actual toString
method created for the enum type Currency . In other words, Java automatically creates
this toString method that returns the name of the coin.
Conversely, suppose that we want our toString method to display the value of the coin
as a number. In this case, we should rewrite the code as follows.
public String toString() {
return value . getValue()+ " that is " +face ;
Now the getValue method is executed to retrieve the value of the coin.
Inside an enum block one can specify a set of constants. These are the possible
values of the type. If it is required that additional information is stored for every
constant, then create an additional variable of this type and appropriate constructor
and getValue method. Note that the constructor must be defined as private .The
reason is that one cannot create an instance of an enum type directly using the new
Let us now go back to our Coin game. We will modify the toString method as follows.
public String toString() {
return (face == Face.TAILS) ? value . toString() : "HEADS" ;
The reason for the modification is that we want the method to return the value of the
coin when the coin is tails and we want the method to return the string HEADS otherwise.
Note that Face.TAILS returns a reference to the constant TAILS of the FACE enum type. In
other words, the values of an enum type can be accessed similarly to the static constants
of a class. Note that now we need to call the toString method explicitly. In this scenario,
Java will not automatically convert the object to a String .
It is also worth examining the getRandomCoinValue method in detail. First of all, note
that it is a private method because we do not want anyone from outside the class to be
aware of its existence. The method generates a random number between 0 and 1. Based on
that value, it returns penny, nickel, dime, or quarter. In other words, it generates a random
value for the coin. Note that the code can also be rewritten as follows.
Search WWH ::

Custom Search