2. What is enum ?
“An Enum is a special or derived (Non-Primitive) Java type
used to define collections of constants.”
In simple terms an enum is a list of named constants
that define a new type which has a fixed set of values.
It is a special class type
An ref variable of an enumeration type can hold only
the values that are defined by the list.
3. How to use?
In the Java programming language, you define an enum type by
using the enum keyword.
For example,
you would specify-
dayOfWeek: SUNDAY, MONDAY, TUESDAY, …
month: JAN, FEB, MAR, APR, …
gender: MALE, FEMALE
compassDirections: NORTH, SOUTH, EAST, WEST
4. Because they are constants, the names of an enum
type's fields are in uppercase letters.
The variable must be equal to one of the values that
have been predefined for it.
enum Season {
WINTER, SPRING, SUMMER, FALL
}
class EnumExample1{
public static void main(String[] args
) {
Season s=Season . WINTER;
System.out.println(s);
}
}
5. When to use?
You should use enum types any time to represent a fixed
set of constants.
Note:
• Java implements enumerations as class type.
• We don't instantiate an enum using new , it acts much like a class,
i.e. you can give it constructors, add instance variable and methods
and even implement interfaces
6. Example of specifying initial value to the enum constants
class EnumExample{
enum Season{
SUNDAY(7), MONDAY(1), FRIDAY(5), SATURDAY(6);
private int value;
private Season( int value){
this.value=value;
}
}
public static void main(String args[]){
for (Season s : Season.values())
System.out.println(s+" "+s.value);
}
}
7. Key Point’s -
1.enum can't inherit another class(all enumerations
automatically inherit java.lang.Enum class)
2.enum cannot be a superclass,i.e. enumeration
can't be extended