I want to take an existing enum and add more elements to it as follows:
enum A {a,b,c} enum B extends A {d} /*B is {a,b,c,d}*/
Is this possible in Java?
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.
No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.
You cannot extend, override or inherit an enum .
4) Enum constants are implicitly static and final and can not be changed once created.
No, you can't do this in Java. Aside from anything else, d
would then presumably be an instance of A
(given the normal idea of "extends"), but users who only knew about A
wouldn't know about it - which defeats the point of an enum being a well-known set of values.
If you could tell us more about how you want to use this, we could potentially suggest alternative solutions.
Enums represent a complete enumeration of possible values. So the (unhelpful) answer is no.
As an example of a real problem take weekdays, weekend days and, the union, days of week. We could define all days within days-of-week but then we would not be able to represent properties special to either weekdays and weekend-days.
What we could do, is have three enum types with a mapping between weekdays/weekend-days and days-of-week.
public enum Weekday { MON, TUE, WED, THU, FRI; public DayOfWeek toDayOfWeek() { ... } } public enum WeekendDay { SAT, SUN; public DayOfWeek toDayOfWeek() { ... } } public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN; }
Alternatively, we could have an open-ended interface for day-of-week:
interface Day { ... } public enum Weekday implements Day { MON, TUE, WED, THU, FRI; } public enum WeekendDay implements Day { SAT, SUN; }
Or we could combine the two approaches:
interface Day { ... } public enum Weekday implements Day { MON, TUE, WED, THU, FRI; public DayOfWeek toDayOfWeek() { ... } } public enum WeekendDay implements Day { SAT, SUN; public DayOfWeek toDayOfWeek() { ... } } public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN; public Day toDay() { ... } }
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