featuresee page 175.)
An enum cannot be declared to extend another type because all enums implicitly extend
java.lang.Enum, which we discuss a little later. Nor can any other type extend an enum (not even another
enum), because all enum types act as if they are implicitly final. An enum can declare that it implements
one or more interfacesin fact all enums are implicitly Serializable (see "Object Serialization" on page
549) and Comparable.
The possible members of an enum include all the class members: fields, methods, and nested types, including
nested enumsthough it should be rare to require such sophistication: The main attraction of enums is their
simplicity. The enum constants themselves are implicitly static fields with the same type as the enum.
Every enum type E has two static methods that are automatically generated for it by the compiler:
public staticE[] values()
Returns an array containing each of the enum constants in the order in which
they were declared.
public staticE valueOf(String name)
Returns the enum constant with the given name. If the name does not match
an enum constant name exactly then an IllegalArgumentException
is thrown.
Note that the length of the array returned by values tells you how many enum constants there are in the
enum, so the getSize method we demonstrated is not needed in practice.
An enum type is not allowed to override the finalize method from Object. Enum instances may never
be finalized (see "Finalization" on page 449).
6.2.1. Enum Modifiers
An enum declaration can be preceded by certain modifiers:
- annotations Annotations and annotation types are discussed in Chapter 15.
access modifiers Nested enum declarations can have any of the access modifiers, while a top-level
enum, as for a top-level class, is either public or in the absence of an access modifier, accessible
only within its own package.
•
static All nested enums are implicitly static because they contain static members. By convention,
the static modifier is always omitted.
•
strict floating point All floating-point arithmetic within an enum declared to be strictfp is
evaluated strictly. See Section 9.1.3 on page 203 for details.
•
When multiple modifiers are applied to the same interface declaration, we recommend using the order listed
above.
An enum cannot be declared abstract because you cannot extend it to provide missing method
implementationshowever, an enum can declare abstract methods. You'll shortly see how this apparent
contradiction is resolved.
An enum also cannot be explicitly declared final, though it acts as if it were final. You'll shortly see why
this is so, too.