Reputation: 5262
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?
Upvotes: 3
Views: 718
Reputation: 308131
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:
public enum Foo {
BAR,
BAZ;
}
then you know that it has exactly two values: BAR
and BAZ
.
If you could extend an enum then you could introduce an ExtendedFoo
enum that adds QUUX
. Now since ExtendedFoo
would be a Foo
, QUUX
would suddenly be a valid Foo
value. And nothing would stop you from adding any number of additional Foo
values.
This means that the compiler can no longer check if your switch
covers all Foo
cases. Similar static analysis steps are also no longer possible. Effectively your enum
would 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 enum
class is not always final
: 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.
Upvotes: 3
Reputation: 258618
Because enums
are completely different, logically, from classes
. You use enums
to group things together, not for logic. Use classes for logic and enums... well... for enumerations.
What enum do you want to extend? Why would you do that? If there is a reason to do this, that means your structure is better suited to be a class.
Upvotes: 1
Reputation: 43108
The common way is to create several enums and join them by implementing one common interface.
public enum One implements MyInterface {
}
public enum Two implements MyInterface {
}
public void process(MyInterface oneOrTwo) {
...
}
Upvotes: 2