I truly understand that it is not able to extend any class to implement an enum, since this would mean to have multiple inheritance. But what I don’t understand is, why the enum classes, created by the compiler when using “enum” instead of “class” are final.
Is there any good reason why enums cannot be extended?
Plus: Is there any way to implement common behavior to different enums without Copy&Paste?
A very important aspect of enums is that the number or values are known at compile time (at least at compile time of the enum).
So if you have an enum like this:
then you know that it has exactly two values:
BARandBAZ.If you could extend an enum then you could introduce an
ExtendedFooenum that addsQUUX. Now sinceExtendedFoowould be aFoo,QUUXwould suddenly be a validFoovalue. And nothing would stop you from adding any number of additionalFoovalues.This means that the compiler can no longer check if your
switchcovers allFoocases. Similar static analysis steps are also no longer possible. Effectively yourenumwould cease to be a special type and there would be very little difference to a normal class with some pre-defined instances.Side note: the generated
enumclass is not alwaysfinal: If (at least) one of your enum values has a value-specific body, then the “base” class will not be final, but the compiler will still prevent you from extending it.