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}]
Rules for enum type
Rules for enum type
- An enum constant specifies an instance of the enum type.
- An enum constant can be optionally followed by a list of arguments and a class body. The class body is an anonymous class which conforms to rules of anonymous classes and:
- It cannot have any constructor.
- It cannot have any abstract methods.
- Instance methods declared in the class body are only accessible if they override accessible methods declared in the enclosing enum type.
- An enum type cannot be declared abstract or final.
- The Enum<E> is the direct superclass of an enum type.
- An enum type can be only declared inside class level, same as class level or in a separate source file. It cannot be declared inside a method or an inner class.
- An enum type can have constructors, methods and variables just like a regular Java class.
Examples for enum type
Examples for enum type
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();
}
No comments:
Post a Comment