I am wondering why in the Java language a class
cannot extend an enum
.
I\'m not talking about an enum
extending an enum<
I think an answer to why they did it this way comes from this question:
In your example, how would you instantiate a MyClass? Enums are never explicitly instantiated (via a new MyEnum()
) by the user. You'd have to do something like MyClass.ASD
but not sure how that would work.
Basically, I don't know what syntax would work for your proposed addition. Which is probably why they made them final etc...
EDIT ADDED
If the author of the original Enum planned ahead (unlikely), and you are not worried too much abut thread safety, you could do something like this: (BTW, I'd probably scream at anybody who actually did this in production code, YMMV)
public enum ExtendibleEnum {
FOO, BAR, ZXC;
private Runnable anotherMethodRunme; // exact Interface will vary, I picked an easy one
// this is what gets "injected" by your other class
public void setAnotherMethodRunMe(Runnable r) { // inject here
anotherMethodRunme= r;
}
public void anotherMethod() { // and this behavior gets changed
anotherMethodRunme.run();
}
}