Java Enum - 10 things to know
Java Enum was one of the best feature added on JDK 1.5 Tiger release along with Generics, Autoboxing and varargs. Enum in Java represents fixed number of well known things e.g. number of day in Week, number of months in calendar year etc. Unlike C and C++ Enum in Java are much powerful and they are not integer constant, Instead Enum are Type like class or interface which provides compile time type safety. In this Java Enum tutorial we will see couple of important points about Java Enum which help to understand Enum better and get most out of it.
Java Enum Concepts
1) Enum in Java are not integer constant, they are classes, similar to any interface or class. Because of this reason Enum in Java provides type-safety and compile time checking which was not possible with enum int pattern.
2) Every Enum in Java extends from java.lang.Enum implicitly and because of this Enum can not extend any other class in Java.
3) Enum in Java doesn't have public constructor. This means you can not create additional instance of Enum instances other than what is created from Enum class itself and available at compile time. Enum can have private constructor though.
4) Enum values or Enum instances are public, static and final in Java. They are compile time constant, which means you can not changes values of Enum instances and further assignment will result in compile time error.
5) Enum in Java can implement interface and override methods. In fact Java Enum implements Comparable interface and override compareTo() method.
6) Enum instance in Java can be compared using == equality operator or equals() method in Java. Enum provide high quality implement for equals() and hashCode and can be used in Set and Map. But for performance reason its best to use EnumMap and EnumSet while storing enum in Collection.
7) When you compare different instances of same Enum type, they are compared in the order on which they are declared in Enum. You can get this order by calling ordinal() method of Enum.
8) Enum provides implicit method like values(), ordinal() and name() which can be used to get all Enum instances as array, order of enum as declared in class and String name of Enum instances in Java.
9) Enum values() method can be used to iterate over enum. It return an array which can be traverse using for-each loop.
10) You can declare methods in Java Enum and you can even override and overload them.
That's all about important features of Java Enum. Enum are much powerful and they have used in different ways in Java programming language. you can use Enum to create thread-safe Singleton in Java. You can also replace your old code which is written using enum int pattern or enum String pattern in Java.
Other Java tutorials you may find useful