enum keyword in java
The ” enum
” keyword is used to define a fixed set of constants.
enum
keyword is introduced in Java 5.
It can be used for set of status in the application, set of some constant names in the project etc.
The general syntax for an enum type is as follows:
- enum <enum_name> {
- <enum_constant_1>,
- <enum_constant_2>,
- ...
- <enum_constant_n>
- <enum_constructor>
- // other variables & methods if required
- }
enum <enum_name> { <enum_constant_1>, <enum_constant_2>, ... <enum_constant_n> <enum_constructor> // other variables & methods if required }
Example
- public enum status {
- CREATED,INPROGRESS,COMPLETED
- }
public enum status { CREATED,INPROGRESS,COMPLETED }
An enum
type containing constructor, method and variable:
- public enum Priority {
- LOW(4),NORMAL(3), HIGH(2), SEVERE(1);
- priority(int priorityNumber) {
- this.priorityNumber = priorityNumber;
- }
- private int priorityNumber;
- public int getPriorityNumber() {
- return this.priorityNumber;
- }
- }
public enum Priority { LOW(4),NORMAL(3), HIGH(2), SEVERE(1); priority(int priorityNumber) { this.priorityNumber = priorityNumber; } private int priorityNumber; public int getPriorityNumber() { return this.priorityNumber; } }
Enum can be iterated as below
- for (Priority priority : Priority.values()) {
- System.out.println(priority);
- }
for (Priority priority : Priority.values()) { System.out.println(priority); }
Points to remember about Java Enum
enum improves type safety
enum can be used in switch
enum can be traversed using enumerations
enum can have fields, constructors and methods as explained above
enum may implement interfaces but can’t extend any class because it internally extends Enum class
Rules to follow for Enum types
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
An enum type can not be declared as abstract
or final
.
The Enum
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.
enum can not be declared inside a method or an inner class.
An enum type can have constructors, methods and variables just like a regular Java class as shown in the above example.