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.*;
|
| C:\roseindia>javac
Employee.java C:\roseindia>java Employee Chandan Ashish Amar Tamana |
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
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Enum Type
Post your Comment