Chapter 1
Understanding enum:
Definition and need of enum
Enum is a type of class which is final. It
is created by using the keyword “enum”. It is used for defining set of named
constants those represents a menu kind of item.
For Example:
Hotel Menu, Bar Menu, Course Menu etc…
Before java 5 these menu items are created
by usin class. Class has a problem in accessing these menu items, that is it
cannot return or print item name as it is declared instead it returns or prints
its value.
For Example:
//Months.java
class Months
{
static
final int JAN =1;
static
final int FEB =2;
public
static void main(String[] args)
{
System.out.println(Months.JAN);
System.out.println(Months.FEB);
}
}
Prints
|
1
|
2
|
Enum is introduced in Java 5 to solve above
problems, it means to print menu item name not value.
Syntax: to create enum data type in java 5
a new keyword “enum” is introduced.
enum <enumName>
{
//menu
items names with "," seperator
;
//normal
all 8 members which you define in a nnormal class
}
Note: For creating above name constants
just use only names do not use any datatype
//Months.java
enum Months{
JAN,
FEB;
}
//year.java
class Year
{
public
static void main(String[]args)
{
System.out.println(Months.JAN);
System.out.println(Months.FEB);
}
Compilation
>javac Year.java
>java Year
Prints:
|
JAN
|
FEB
|
What is the data type of named constants in
enum ?
Its data type is current enum type. It is
added by compiler automatically.
For example
In the enum Months, Its named constants are
converted as shown below
public static final Months JAN;
public static final Months FEB;
Please Note:
- Enum is a final class hence cannot be inherited.
- It is sub class of Java.lang.Enum.
- It is a abstract class which is the default super class for every enum type classes. Also it is implementing from Comparable and Serializable interfaces.
- Since every enum type is Comparable so we can add its objects to collection TreeSet object, also it can be stored in file as it is Serializable type.
No comments:
Post a Comment