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}]

 

Some rules for enum type in Java:

      • 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.

 

Java enum type examples:

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.

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.