Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how do I get the value of an enum inside the enum itself?

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.
    }
}
like image 362
Matthew Avatar asked Feb 23 '10 21:02

Matthew


People also ask

Can we have enum inside enum in Java?

yes, but you need to know that. no way to easily iterate through all of the enum instances.

Can we define enum inside a enum?

We can an enumeration inside a class. But, we cannot define an enum inside a method.

How do you access methods inside an enum?

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.


1 Answers

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(); 
    } 
  } 
} 
like image 151
maerics Avatar answered Sep 29 '22 07:09

maerics