Java Programming/Keywords/enum
Appearance
From Wikibooks, open books for an open world
Computer code
/** Grades of courses */ enumGrade{A,B,C,D,F}; // ... privateGradegradeA=Grade.A;
This enumeration constant then can be passed in to methods:
Computer code
student.assignGrade(gradeA); /** * Assigns the grade for this course to the student * @param GRADE Grade to be assigned */ publicvoidassignGrade(finalGradeGRADE){ grade=GRADE; }
An enumeration may also have parameters:
Computer code
publicenumDayOfWeek{ /** Enumeration constants */ MONDAY(1),TUESDAY(2),WEDNESDAY(3),THURSDAY(4),FRIDAY(5),SATURDAY(6),SUNDAY(0); /** Code for the days of the week */ privatebytedayCode=0; /** * Private constructor * @param VALUE Value that stands for a day of the week. */ privateDayOfWeek(finalbyteVALUE){ dayCode=java.lang.Math.abs(VALUE%7); } /** * Gets the day code * @return The day code */ publicbytegetDayCode(){ returndayCode; } }
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:
Computer code
publicenumDayOfWeekimplementsRunnable{ MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY; /** * Run method prints all elements */ publicvoidrun(){ System.out.println("name() = "+name()+ ", toString() = \""+toString()+"\""); } }