Implementing toString on Java enums

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-03-23T04:10:31Z Indexed on 2010/03/23 4:21 UTC
Read the original article Hit count: 360

Filed under:
|

Hello

It seems to be possible in Java to write something like this:

 private enum TrafficLight {
  RED,
  GREEN;

  public String toString() {
   return //what should I return here if I want to return
                               //"abc" when red and "def" when green?
  }
 }

Now, I'd like to know if it possible to returnin the toString method "abc" when the enum's value is red and "def" when it's green. Also, is it possible to do like in C#, where you can do this?:

 private enum TrafficLight {
  RED = 0,
  GREEN = 15
  ...
 }

I've tried this but it but I'm getting compiler errors with it.

Thanks

© Stack Overflow or respective owner

Related posts about enums

Related posts about java