Java Reference
In-Depth Information
values of the variable
value
.The
enum
construct allows us to create a better solution that
overcomes both shortcomings.
The
enum
construct is similar to a class in that it allows us to create a user-defined type.
A class usually combines several types. For example, an
Employee
class can combine the
name of the person (of type
String
) and the age of the person (of type
int
). Conversely, an
enum
focuses on a single primitive type and enumerates a finite number of allowed values.
An example of how to use the
enum
construct in our program follows.
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 ;
}
}
enum Face
{
HEADS (
true
), TAILS(
false
);
private boolean
value ;
private
Face(
boolean
value)
{
this
. value = value ;
public boolean
getValue()
{
return
value ;
}
}
public class
Coin
{
public static final double
DEFAULT BIAS = 0 . 5 ;
private
Currency value ;
private
Face face ;
private double
bias ;
public
Coin()
{
this
. b i a s = DEFAULT BIAS ;
this
. value = getRandomCoinValue () ;
flip();
}
public
Coin(Currency value )
{
this
. value = value ;
this
. b i a s = DEFAULT BIAS ;
flip();
}
public
Coin(Currency value ,
double
bias)
{
this
. value = value ;
this
.bias = bias;
flip();