Roedy Green said:
Has anyone figured out how you extend an enum, e.g.
1. a class like the base but with more enum constants.
2. a class like the base but with more methods on each enum constant.
Nope, neither of these are possible.
Regarding #1:
If you think about it, inheritance goes the wrong direction for adding
enum constants. A subclass needs to meet the requirements for a
superclass, plus add additional capabilities or constraints. The most
important facet of an enum type is that it is limited to a finite set of
values. A subtype of an enumeration would need to keep that constraint
plus add more... so it might make sense for a subtype of an enum to
define a limited subset of the possible values in its supertype... but
it breaks type safety for a subtype to add more possible contents.
In order to sensibly implement an expansion of possibilities for enum
constants, something opposite to subtyping would be needed. You'd need
implicit conversion from the base type to the derivative type, but NOT
from the derivative type to the base type. Logically, this wouldn't fit
with the 'extends' keyword... you'd need to add a new keyword, like
'expands', just for that purpose. This also really screws with method
overload resolution, which depends on the possibility of various
implicit conversions.
IMO, it was quite sensible of Sun to avoid this can of worms and refuse
to provide a mechanism for adding possibilities to an enum. We just
don't need that kind of complexity in the type system.
Regarding #2: You're asking for something that unequivocally isn't
possible in Java; that is, the ability to write code that modifies the
methods or fields of a class that is not even aware of your code. You
can't do this, for the same reason that I can't write a class A that
adds methods to existing objects of class B.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation