Enum Type

Enum
is
a keyword which was introduced in Java 5. It is a particular
type of class whose instances are only those objects which are members of that
enum. The super class of all enum objects is java.lang.Enum, apart from this enum
can not be extended.
There is another important feature that is every enum
requires support from the class library. When a program compiles and compiler
encounters an enum type, it generates a class that extends the java.lang.Enum,
which is a library class.
Here we try to illustrate the use of enum through a simple
example, in which enum works as special class named "Names"
with many instances. After that we enumerate all the possible values for a variable of
enum type like Chandan, Ashish, Amar, Tamana via loop. Which is
displayed by the object of "Names" named "count".
Here is the Code of the Example :
"Example.java"
import java.lang.*;
public class Employee{
public enum Names {Chandan, Ashish, Amar, Tamana}
public static void main(String[] args){
for (Names count : Names.values()){
System.out.println(count);
}
}
}
|
Here is the Output of the Example :
C:\roseindia>javac
Employee.java
C:\roseindia>java Employee
Chandan
Ashish
Amar
Tamana
|
Download This Example :
In the above example enum declaration generates a
special class "Names", which automatically implements the Comparable<Names>
and Serializable interfaces, and provides several members including:
-
Static variables in above example are Chandan, Ashish, Amar
and Tamana.
-
Static method in above example is values() that
retrieves the values included in enum.
-
Static method valueOf(String) returns
the appropriate enum for the string passed in.
-
Appropriately overloaded equals(), hasCode(),
toString(), and compareTo() methods.
This approach has many advantages including
- enum provides compile-time type safety.
- Compact, efficient declaration as well as it provides a separate namespace for each enumerated values.
- enum constants can be used wherever objects can be
used as well as it provide runtime efficiency.
There is an additional feature of enum that two classes have been added to
java.util. EnumSet can be used for implementation of
enums and EnumMap can be use with enum
keys.

|