Datasheet

case linux:
System.out.println(“You chose Linux!”);
break;
case macintosh:
System.out.println(“You chose Macintosh!”);
break;
default:
System.out.println(“I don’t know your OS.”);
break;
}
}
}
The java.lang.Enum class implements the Comparable and Serializable interfaces. The details of
comparing enumerations and serializing them to a data source are already handled inside the class. You
cannot mark an
enum as abstract unless every constant has a class body, and these class bodies over-
ride the abstract methods in the
enum. Also note that enumerations cannot be instantiated using new.
The compiler will let you know that
enum types may not be instantiated.
Java introduces two new collections,
EnumSet and EnumMap, which are only meant to optimize the per-
formance of sets and maps when using
enums. Enumerations can be used with the existing collection
classes, or with the new collections when optimization tailored to enumerations is desired.
Methods can be declared inside an
enum. There are restrictions placed on defining constructors, how-
ever. Constructors can’t chain to superclass constructors, unless the superclass is another
enum. Each
constant inside the
enum can have a class body, but because this is effectively an anonymous class, you
cannot define a constructor.
You can also add attributes to the enumeration and to the individual
enum constants. An enum constant
can also be followed by arguments, which are passed to the constructor defined in the
enum.
Here’s an example enumeration with fields and methods:
enum ProgramFlags {
showErrors(0x01),
includeFileOutput(0x02),
useAlternateProcessor(0x04);
private int bit;
ProgramFlags(int bitNumber)
{
bit = bitNumber;
}
public int getBitNumber()
{
return(bit);
}
}
public class EnumBitmapExample {
public static void main(String args[])
25
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 25