3.11 Extending an Enum
It's often easy to define a hierarchy of enumerations. In this scenario, one
enum represents a base type of allowed values. Subclasses of that enum
would add additional values to the base enum, perhaps specialized to a
certain task.
3.11.1 How do I do that?
Here's another one of those pesky, "You don't" labs. Tiger does not allow
extension of an enum. For example, consider Example 3-12, a simple
extension of the Grade enum defined back in Example 3-1.
Example 3-12. Extending the Grade enum
In theory, this would take the values Grade.A, Grade.B, and so forth, and
package com.oreilly.tiger.ch03;
public enum CollegeGrade extends Grade { DROP_PASSING, DROP_FAILING }
add to them two new values, CollegeGrade.DROP_PASSING and
CollegeGrade.DROP_FAILING. However, you'll get compilation errors if
you try this:
NOTEUse the Ant
compile-ch03-errors:
[echo] Compiling all Java files...
[javac] Compiling 13 source files to classes
[javac] src\ch03\CollegeGrade.java:3: '{' expected
[javac] public enum CollegeGrade extends Grade {DROP_PASSING, DROP_
FAILING}
[javac] ^
[javac] src\ch03\CollegeGrade.java:3: <identifier> expected
[javac] public enum CollegeGrade extends Grade {DROP_PASSING, DROP_
FAILING}
[javac]
^
[javac] 2 errors
target "compilech03-
errors" to try
and compile the
CollegeGrade.
java source file.
3.11.2 What about...
...using a class to extend an enum, instead of another enum? That
doesn't work either. There's just no getting around this limitation, at least
that I've been able to find..NOTEIf you find a
sneaky way to
extend an enum,
let us know! We'll
add it to the
next edition.