Java Programming/Keywords/enum
/** Grades of courses */
enum Grade { A, B, C, D, F };
// ...
private Grade gradeA = Grade.A;
|
This enumeration constant then can be passed in to methods:
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;
}
|
An enumeration may also have parameters:
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;
}
}
|
It is also possible to let an enumeration implement interfaces other than java.lang.Comparable
and java.io.Serializable
, which are already implicitly implemented by each enumeration:
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() + "\"");
}
}
|