Let's say we have an enumerated type Result:
enum Result { Pass, Fail }When we do a print of either type, like:
System.out.println(Result.Pass) we get a word "Pass" which is not so user-friendly.
There are many ways to add a label to each enumeration and here are three common ones:
enum Result {
Pass, Fail;
String getLabel() {
switch(this) {
case Pass : return "You are passed";
case Fail : return "You are failed";
}
throw new AssertionError("Unknown result: " + this);
}
}enum Result {
Pass("You are passed"), Fail("You are failed");
Result(String s) { label = s; }
String label;
String getLabel() { return label; }
}enum Result {
Pass { String getLabel() { return "You are passed"; }},
Fail { String getLabel() { return "You are failed"; }};
abstract String getLabel();
}All of them print "You are passed" when displaying
Result.Pass.getLabel(). I believe the first approach is relatively slower since it needs to do checking, although it is cleaner at the type definition. Second approach make use of constructor but an instance variable has to be introduced, it's also not so extensible since it would end up with a few constructors when more aliases are required. I prefer the last approach as it looks more flexible.