Jump to content
Wikibooks The Free Textbook Project

Java Programming/Keywords/enum

From Wikibooks, open books for an open world

This is the current revision of this page, as edited by Strange quark (discuss | contribs) at 18:26, 4 July 2017 (Fix categorization). The present address (URL) is a permanent link to this version.

Revision as of 18:26, 4 July 2017 by Strange quark (discuss | contribs) (Fix categorization)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)



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()+"\"");
}
}

AltStyle によって変換されたページ (->オリジナル) /