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.
}
}
yes, but you need to know that. no way to easily iterate through all of the enum instances.
We can an enumeration inside a class. But, we cannot define an enum inside a method.
Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can't create child enums. We can declare the main() method inside the enum.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With