跳至内容

Java 编程 / 关键字 / 枚举

来自 Wikibooks,开放世界中的开放书籍



Computer code
/** Grades of courses */
  enum Grade { A, B, C, D, F };
  // ...
  private Grade gradeA = Grade.A;


然后,可以将此枚举常量传递给方法

Computer code
student.assignGrade(gradeA);
  /**
   * Assigns the grade for this course to the student
   * @param GRADE  Grade to be assigned
   */
  public void assignGrade(final Grade GRADE) {
    grade = GRADE;
  }


枚举也可以有参数

Computer code
public enum DayOfWeek {
  /** Enumeration constants */
  MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(0);

  /** Code for the days of the week */
  private byte dayCode = 0;

  /**
   * Private constructor
   * @param VALUE  Value that stands for a day of the week.
   */
  private DayOfWeek(final byte VALUE) {
    dayCode = java.lang.Math.abs(VALUE%7);
  }
 
  /**
   * Gets the day code
   * @return  The day code
   */
  public byte getDayCode() {
    return dayCode;
  }
}


还可以让枚举实现除 java.lang.Comparablejava.io.Serializable 之外的其他接口,这些接口已由每个枚举隐式实现

Computer code
public enum DayOfWeek implements Runnable {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
 
  /**
   * Run method prints all elements
   */
  public void run() {
    System.out.println("name() = " + name() +
      ", toString() = \"" + toString() + "\"");
  }
}
华夏公益教科书