I am somewhat new to enums in Java, and I am trying to override toString() so that it can return special cases for an enum with creating code for each case:
enum TestEnum {
One, Two, Three,
Exclamation, Ampersand, Asterisk;
public String toString() {
if (this == Ampersand) return "&";
if (this == Exclamation) return "!";
if (this == Asterisk) return "*";
return null; // return toString(); ???
}
If I use toString as the default return statement, I obviously get a StackOverflowError. Is there a way to get around this and return any cases not included in the toString()?
Is there a way to get around this and return any cases not included in the toString()?
I think you just want:
return super.toString();
Then it won't call itself - it'll just use the superclass implementation.
However, I'd change the implementation to make the string representation a field within the enum value, specified at construction time where necessary:
enum TestEnum {
One, Two, Three,
Exclamation("!"), Ampersand("&"), Asterisk("*");
private final String name;
private TestEnum(String name) {
this.name = name;
}
private TestEnum() {
name = super.toString();
}
@Override public String toString() {
return name;
}
}
Tested with:
public class Test {
public static void main(String [] args){
for (TestEnum x : TestEnum.values()) {
System.out.println(x);
}
}
}
Output:
One
Two
Three
!
&
*
See more on this question at Stackoverflow