Enum Types in Java
Enum was introduced in java 5. Enum types in java is a special type of class to define collection of constants. Variables in enum are constants so there name should be in uppercase letters. In java we define an enum type by using the enum keyword. Enum types in java is used to represent a fixed set of constants.
An example of java enum:-
public class EnumTest{ public enum Languages { JAVA, PYTHON, RUBY, JAVASCRIPT, PHP, SQL; } public static void main(String[] args){ System.out.println("example of enum types in java"); for(Languages languages : Languages.values()) System.out.println(languages); } }
output:-
Some special methods are added to the enum class at compile time like static values method in the above example are added by the compiler. The values method returns the array of the enum type in the order in which the enum is declared.
If you want to specify values of enum constants then above example will be modified as:-
public class EnumTest{ public enum Languages { JAVA("java"), PYTHON("python"), RUBY("ruby"), JAVASCRIPT("javascript"), PHP("php"), SQL("sql"); private String name; Languages(String name){ this.name=name; } public String getName(){ return name; } } public static void main(String[] args){ System.out.println("example of enum types in java"); for(Languages language : Languages.values()) System.out.println("name: "+language+" value: "+language.name); } }
output:-
example of enum types in java name: JAVA value: java name: PYTHON value: python name: RUBY value: ruby name: JAVASCRIPT value: javascript name: PHP value: php name: SQL value: sql
Some points about enum
- constructor in enum class must be private.
- constants in enum are implicitly static and final.
- enum can be used in switch statement.
- in enum we can compare constants using “==” equality operator.
- enums are implicitly final subclass of java.lang.Enum
- enum is implicitly static, if it is a member of the class.
- abstract methods can also be define inside the enum class.
- enum can also implement the interface.
- semicolon is optional at the end of enum constant declaration.
- enum constructor can be overloaded.
- enum can not be declared inside the method.
- enum can not be accessed using the new operator because it’s constructor is private.