|
What
is Enum?
Enum is a type like class or interface in java. enum is a keyword in java. enum types should be used in place of constants as they are type-safe.
Let's look at the following example:
public enum Day{ SUNDAY, MONDAY }
Here SUNDAY and MONDAY are of type Day. This is like
creating two objects of type "Day". Compiler
internally calls the constructor when creating SUNDAY and
MONDAY enum types.
Iterating or accessing enum types
for( Day p : Day.values() ){ System.out.println(p); System.out.println(p instanceof Day); }
output:
SUNDAY true MONDAY true
Advantages of enum
Let's dive further and see
how to assign values to the enum types:
Let's say we want to assign day of the week 1 to
SUNDAY and 2 to MONDAY. As mentioned above compiler calls
the constructor when creating enum types. As we want to
provide the value's to the enum types, we will have to
provide the constructor.
package com.visionjava; public enum DayOfWeek{ SUNDAY(1), MONDAY(2); private int dayOfWeek; DayOfWeek(int val){ dayOfWeek = val; } public int getDayOfWeek(){ return dayOfWeek; } }
So the compiler will call the constructor ( DayOfWeek(int val)
)
when initializing SUNDAY(1)
and MONDAY(2). The value "1" and "2"
are assigned to dayOfWeek variable in the enum.
Remember: enum's are special types like class which can
have methods and variables.
for(DayOfWeek d : DayOfWeek.values()){ System.out.println(d + " : " + d.getDayOfWeek()); }
Output:
SUNDAY : 1 MONDAY : 2 |