is there a simple way to subclass a Java enum
?
I ask this because I have like 10 of them that implement the same interface but they also have the same implementation for some methods so I would like to reuse the code by placing all the same implementations in middle object that extends Enum
and it is also the superclass of all the others I need.
Maybe it is not so straightforward as I think?
Thank in advance
We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.
You cannot extend, override or inherit an enum .
The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them.
You cannot override enums, and C# does not support return type covariance.
You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.
This in brief states that every instance of a subclass should be acceptable whenever an instance of a superclass is expected. If you add a new enum member in an enum subclass, that clearly can't be accepted by someone knowing only the super enum.
For more details and possible alternatives, see this earlier answer of mine.
In your concrete case, @Jason's suggestion may offer a good solution (+1 for him :-)
Good point, I was a bit sloppy above :-) Implementation-wise you are right. However, from the logical point of view an enum type is fully described by the set of its valid values. And generally, a proper subclass is a specialization of its superclass. In other words, the set of valid subclass instances is (should be) always a subset of the superclass instance set. (Every dog is an animal, but not every animal is a dog.)
I ask this because I have like 10 of them that implement the same interface but they also have the same implementation for some methods so I would like to reuse the code by placing all the same implementations in middle object that extends Enum and it is also the superclass of all the others I need.
How about using a static helper class?
interface Animal
{
public void speak();
}
class AnimalHelper
{
public static void speakHelper(Animal animal) {
// common methods here
}
}
enum Dog implements Animal { SCHNAUZER, LABRADOR, ST_BERNARD, DACHSHUND;
@Override public void speak() {
AnimalHelper.speakHelper(this);
}
};
enum Bird implements Animal { OWL, FINCH, DUCK, GOOSE; }
@Override public void speak() {
AnimalHelper.speakHelper(this);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With