Enumerations was added to Java language in JDK5. Enumeration means
a list of named constant. In Java, enumeration defines a class type. An
Enumeration can have constructors, methods and instance variables. It is
created using enum keyword. Each enumeration constant is public, static and final by
default. Even though enumeration defines a class type and have constructors,
you do not instantiate an enum using new.
Enumeration variables are used and declared in much a same way as you do a
primitive variable.
How to Define and Use an Enumeration
- An
enumeration can be defined simply by creating a list of enum variable. Let
us take an example for list of Subject variable, with different subjects
in the list.
enum
Subject //Enumeration
defined
{
Java, Cpp, C, Dbms
}
2.
Identifiers Java, Cpp, C and Dbms are
called enumeration constants. These are public, static final by
default.
- Variables
of Enumeration can be defined directly without any new keyword.
Subject sub
Example of Enumeration
enum
WeekDays
{
sun, mon, tues, wed, thurs, fri, sat }
class
Test
{
public static void main(String args[])
{
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is "+wk);
}
}
Values(
) and ValueOf( ) method
All
the enumerations have values() and valueOf() methods
in them. values() method returns an array of enum-type containing all
the enumeration constants in it. Its general form is,
public
static enum-type[ ] values()
valueOf() method
is used to return the enumeration constant whose value is equal to the string
passed in as argument while calling this method. It's general form is,
public
static enum-type valueOf (String str)
Points
to remember about Enumerations
- Enumerations are of
class type, and have all the capabilities that a Java class has.
- Enumerations can
have Constructors, instance Variables, methods and can even implement
Interfaces.
- Enumerations are not
instantiated using new keyword.
- All Enumerations by
default inherit java.lang.Enum class.
No comments:
Post a Comment