Implementing toString on Java enums

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
   TrafficLight(String name){string = name;}

   // the toString just returns the given name
   @Override
   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.


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; }
}

Also if You need to get lowercase string value of enum ("red", "green") You can do it as follows:

private enum TrafficLight {
  RED,
  GREEN;

  @Override
  public String toString() {
   return super.toString().toLowerCase();
  }
}