Home United States USA — software Understanding Enumeration in Java – Developer.com

Understanding Enumeration in Java – Developer.com

370
0
SHARE

Learn how enumerations can be utilized in Java.
Enumeration is a recent (from JDK5) inclusion into the family of Java APIs. It basically represents a list of named constants. Apart from Java, almost all other prominent programming languages have the feature of enumeration. Although Java has the final keyword to represent constants, enumeration was included as a convenience to meet many of the streamlined needs of the programmer. This article tries to provide the background information and show how enumerations can be utilized in Java.
Unlike the features of enumeration in other languages, the enumeration designated by the keyword enum in Java represents a special type of class. This inherent capability bolstered the principle of expansion in Java. Because it is a class type, it has a constructor, methods, and instance variables associated with it.
The values defined by the enum are constant. This means they are implicitly static and final. It is not possible to change the values after declaration. The enum is ideally used to represent a set of fixed named constants. For example, to enumerate a list of gender varieties, we may write:
The identifiers Male , Female , and Third are called enumeration constants. As stated earlier, they are by default public static and final members of the enum class. These constants declared are of self typed. We can declare a enum variable as
and can assign a value as
We also can use a comparison operator as such:
Or, use it with the switch statements, as in this example:
Observe that we have not used any qualifier, such as Gender. Male , with the case statement; instead, we used only the named constant Male. This is possible because, when we have declared gender with the switch , statement it implicitly recognizes the type of the enum constants.

Continue reading...