Here's what I am looking to accomplish, I have a class that has an enum of some values and I want to subclass that and add more values to the enum. This is a bad example, but:
public class Digits { public enum Digit { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } public class HexDigits extends Digits { public enum Digit { A, B, C, D, E, F } }
so that HexDigits.Digit contains all Hex Digits. Is that possible?
Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
In byte code, any enum is represented as a class that extends the abstract class java. lang. Enum and has several static members. Therefore, enum cannot extend any other class or enum : there is no multiple inheritance.
Enum, it can not extend any other class or enum and also any class can not extend enum. So it's clear that enum can not extend or can not be extended. But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface.
No it's not possible. The best you can do is make two enums implement and interface and then use that interface instead of the enum. So:
interface Digit { int getValue(); } enum Decimal implements Digit { ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE; private final int value; Decimal() { value = ordinal(); } @Override public int getValue() { return value; } } enum Hex implements Digit { A, B, C, D, E, F; private final int value; Hex() { value = 10 + ordinal(); } @Override public int getValue() { return value; } }
No.
Enums cannot be subclassed.
The reasoning here is that an enumeration defines a fixed number of values. Subclassing would break 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