- constructors, private fields, methods, addressing the "separations of concerns" - how about Enum.valueOf(enumClass, text.toUpperCase()) to avoid the "classic shadow array of string literals"?
Here is an example of what can be achieved by Java enums
enum Type {
ANIMAL(null),
MAMMAL(ANIMAL),
DOG(MAMMAL) {
public void makeNoise() {
System.out.println("Woof");
}
},
CAT(MAMMAL) {
public void makeNoise() {
System.out.println("Meow");
}
};
private Type parent;
Type(Type parent) {
this.parent = parent;
}
public boolean isA(Type type) {
if(this == type) return true;
if(parent != null) return parent.isA(type);
return false;
}
public void makeNoise() { }
}
assert Type.DOG.isA(Type.MAMMAL) == true;
assert Type.CAT.isA(Type.DOG) == false;
Type.CAT.makeNoise(); // "Meow"There is very little reason to use an enum over classes in this example. It's rare that I've seen a Java class style enum that wouldn't have been better served by classes (including some that I've written myself and regretted!)
If the fact that enums are closed ever presents a problem, then it's a good indication that you shouldn't be using enums. That's not a problem with enums, it's just a bad design decision that needs to be reversed.
Agreed that Vehicle is a poor choice for an enum, because it's something that isn't really closed. But if you're modelling something like states of a TCP connection, there's nothing dangerous about it being closed.
I got bit pretty hard before trying to design an annotation-driven convention for a library I was writing (I had been writing a lot of Python for a while) and realized I'd have to squash a bunch of my carefully arranged classes into an enum. You run into similar problems when marshalling your objects to, say, a Thrift structure definition.