In Java, how do I get the value of an enum inside the enum itself?
enums, java, tostring
Solution
public enum Color {
RED("R"),
GREEN("G"),
BLUE("B");
private final String str;
private Color(String s){
str = s;
}
@Override
public String toString() {
return str;
}
}
You can use constructors for Enums. I haven't tested the syntax, but this is the idea.
Problem
I want to override `toString()` for my enum, `Color`. However, I can't figure out how to get the value of an instance of `Color` inside the `Color` enum. Is there a way to do this in Java? Example: ``` public enum Color { RED, GREEN, BLUE, ... public String toString() { // return "R" for RED, "G", for GREEN, etc. } } ```