tags:

views:

93

answers:

2

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

+8  A: 

You can do it as follows:

private enum TrafficLight {
   // using the constructor defined below
   RED("abc"),
   GREEN("def");

   // Member to hold the name
   private String string;

   // constructor to set the string
   private TrafficLight(String name){string = name;}

   // the toString just returns the given name
   public String toString() {
       return string;
   }
}

You can add as many methods and members as you like. I believe you can even add multiple constructors. All constructors must be private.

An enum in Java is basically a class that has a set number of instances.

jjnguy
+3  A: 

Ans 1:

enum TrafficLight {
  RED,
  GREEN;

  @Override
  public String toString() {
    switch(this) {
      case RED: return "abc";
      case GREEN: return "def";
      default: throw new IllegalArgumentException();
    }
  }
}

Ans 2:

enum TrafficLight {
  RED(0),
  GREEN(15);

  int value;
  TrafficLight(int value) { this.value = value; }
}
missingfaktor
Can also override `toString` in each instance, although that adds to the number of classes. And probably isn't that clean, but good for related situations.
Tom Hawtin - tackline