In Java, the enum keyword is used to declare a new enumeration type. This keyword has been introduced since Java 5. The declaration syntax for an enum type is as follows:
enum <name> {
<enum_constant_1>,
<enum_constant_2>,
...
<enum_constant_n>
<enum_constructor>
// other variables & methods as usual
}An enum constant can be declared as follows:
<constant_name>[(arguments)] [{class body}]
A simplest enum type declared inside a class:
class Foo {
enum DayOfWeek {MON, TUE, WED, THU, FRI, SAT, SUN};
}A simple enum type declared in a separate Java file:
public enum ErrorCode {
LOW, HIGH, SEVERE
}An enum type which contains constructor, method and variable:
enum Day {
MON(1), TUE(2), WED(3), THU(4), FRI(5), SAT(6), SUN(7);
Day(int dayNumber) {
this.dayNumber = dayNumber;
}
private int dayNumber;
public int getDayNumber() {
return this.dayNumber;
}
}An enum type with class body for each enum constant:
enum Priority {
LOW {
int getPriorityNumber() {
return 0;
}
},
NORMAL {
int getPriorityNumber() {
return 1;
}
},
HIGH {
int getPriorityNumber() {
return 2;
}
},
SEVERE {
int getPriorityNumber() {
return 3;
}
};
abstract int getPriorityNumber();
}See all keywords in Java.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.