Introduction to the Java enumeration class enum

  • 2020-04-01 03:48:59
  • OfStack

Enum is introduced by JDK1.5, and public static final int enum_value is used to replace enumeration class. Enum is a special class that inherits the class java.lang.enum by default. Like other ordinary classes, enums can also have member variables, methods, constructors, and one or more interfaces. The difference is:

1. If you have a constructor, you must modify it with private.
2. Enumeration classes cannot be subclassed.
3. All instances of an enumeration class must show the definition on the first line. The system will automatically add public static final to these instances without requiring the programmer to show the definition.
4. The enumeration class provides the values() method by default to facilitate traversal of all enumeration values

Methods in enum (methods provided by enum) :

Public final int compareTo(E o) compares enumerated values of the same type
Public final int ordinal() returns the index value of the enumeration, with the first enumeration value starting from zero.
Public final String name() returns the enumeration instance name
Public String toString() returns the enumeration output name

Traffic light example


public enum TrafficLight {
  RED(" red "), YELLOW(" huang "), GREEN(" green ");
  private String name;
  private TrafficLight(String name) {
    this.name = name;
  }
  public String getName() {
    return name;
  }
  public void jude(TrafficLight light) {
    switch (light) {
    case RED:
      System.out.println("stop");
      break;
    case YELLOW:
      System.out.println("go");
      break;
    case GREEN:
      System.out.println("wait");
      break;
    default:
      break;
    }
  }
  public static void main(String[] args) {
    for (TrafficLight e : TrafficLight.values()) {
      System.out.println(e.name());
    }
  }
}

Related articles: