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:-

output:-
enum types in java

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:-

output:-

Some points about enum

  1. constructor in enum class must be private.
  2. constants in enum are implicitly static and final.
  3. enum can be used in switch statement.
  4. in enum we can compare constants using “==” equality operator.
  5. enums are implicitly final subclass of java.lang.Enum
  6. enum is implicitly static, if it is a member of the class.
  7. abstract methods can also be define inside the enum class.
  8. enum can also implement the interface.
  9. semicolon is optional at the end of enum constant declaration.
  10. enum constructor can be overloaded.
  11. enum can not be declared inside the method.
  12. enum can not be accessed using the new operator because it’s constructor is private.

Leave a Reply

Your email address will not be published. Required fields are marked *