I have written a Java enum where the values have various attributes. These attributes could be stored in any of the following ways:
Using fields:
enum Eenum {
V1(p1),
V2(p2);
private final A attr;
public A attr() { return attr; }
private Eenum(A attr) {
this.attr = attr;
}
}
Using abstract methods:
enum Eenum {
V1 {
public A attr() { return p1; }
},
V2 {
public A attr() { return p2; }
}
public abstract A attr();
}
Using class level map:
enum Eenum {
V1,
V2;
public A attr() { return attrs.get(this); }
private static final Map<Eenum, A> attrs;
static {
ImmutableMap.Builder<Eenum, A> builder = ImmutableMap.builder();
builder.put(V1, p1);
builder.put(V2, p2);
attrs = builder.build();
}
}
How should I decide when to prefer which?
Thanks!
Yes, you can define abstract methods in an enum declaration if and only if all enum values have custom class bodies with implementations of those methods (i.e. no concrete enum value may be lacking an implementation).
Enums can define abstract methods, which each enum member is required to implement. This allows for each enum member to define its own behaviour for a given operation, without having to switch on types in a method in the top-level definition.
Can Enum extend a class in java? Enum cannot extend any class in java,the reason is, by default Enum extends abstract base class java.
Which class does all the Enums extend? Explanation: All enums implicitly extend java. lang. Enum.
I would do the one which you think is the simplest.
In general I don't write code which can be implemented using data. I would use the first one.
My actual use case has some attributes which are not relevant for all enum values
You can use a combination of these approaches if it makes sense on a per attribute basis.
A fourth option is to not have an abstract method.
enum Eenum {
V1 {
public A attr() { return p1; }
},
V2 {
public A attr() { return p2; }
},
V3, V4, V5, V6;
public A attr() { return defaultA; }
}
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