Java Reference
In-Depth Information
}
public void
flip()
{
face = (bias
<
Math . random ( ) ) ? Face .HEADS : Face . TAILS ;
// true is
heads
}
private
Currency getRandomCoinValue ()
{
double
randomNumber = Math . random( ) ;
if
(randomNumber
<
0.25)
{
return
Currency .PENNY;
if
(randomNumber
<
0.5)
{
return
Currency .NICKEL;
if
(randomNumber
<
0.75)
{
return
Currency .DIME;
return
C u r r e n c y . QUARTER ;
}
public
String toString()
{
return
value+
" that is "
+face ;
}
public int
getValue ()
{
return
value . getValue() ;
}
public boolean
isHeads ()
{
return
( f a c e == F a c e . HEADS ) ;
}
}
If you create a penny that is heads and try to print it, the
toString
method will return
“PENNY that is HEADS”. As you can see, we have eliminated the switch statement. Next,
let us examine in details the
enum
construct.
enum Currency
{
PENNY ( 1 ) , NICKEL ( 5 ) , DIME ( 1 0 ) , QUARTER ( 2 5 ) ;
private int
value ;
private
Currency(
int
value)
{
this
. value = value ;
}
public int
getValue ()
{
return
value ;
}
}
The definition is similar to that of a class. The only difference is that the first line defines
a set of constants. A number that each constant maps to can be specified in parentheses. If
this mapping is specified, then you must define a variable of this type (in our case
int
)and
a constructor that sets the value of the variable. Note that the constructor must be private.
Alternatively, one can specify an
enum
type as follows.
enum Currency
{