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 Str开发者_Python百科ing toString() {
// return "R" for RED, "G", for GREEN, etc.
}
}
You can also switch on the type of this
, for example:
public enum Foo {
A, B, C, D
;
@Override
public String toString() {
switch (this) {
case A: return "AYE";
case B: return "BEE";
case C: return "SEE";
case D: return "DEE";
default: throw new IllegalStateException();
}
}
}
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.
Enum.name()
- who'd of thunk it?
However, in most cases it makes more sense to keep any extra information in an instance variable that is set int the constructor.
Use super
and String.substring()
:
public enum Color
{
RED,
GREEN,
BLUE;
public String toString()
{
return "The color is " + super.toString().substring(0, 1);
}
}
Java does this for you by default, it returns the .name() in .toString(), you only need to override toString() if you want something DIFFERENT from the name. The interesting methods are .name() and .ordinal() and .valueOf().
To do what you want you would do
.toString(this.name().substring(1));
What you might want to do instead is add an attribute called abbreviation and add it to the constructor, add a getAbbreviation() and use that instead of .toString()
I've found something like this (not tested tho):
public enum Color {
RED{
public String toString() {
return "this is red";
}
},
GREEN{
public String toString() {
return "this is green";
}
},
...
}
Hope it helps a bit !
精彩评论