|
|
|
|
|
by geonik
4083 days ago
|
|
I second that; Java has solutions for all problems described by this post. - 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!)