Enums in java are mainly used for grouping similar kind of constants as a one unit. constants means static and final. Enums are introduced in JDK 1.5 onward. Before that similar kind of constants are grouped by declaring them as static and final in one class. Below example shows how the constants will look without enums.
Older Version:
Older Version:
class
ConstantsWithoutEnums
{
public
static
final
String north =
"NORTH"
;
public
static
final
String south =
"SOUTH"
;
public
static
final
String east =
"EAST"
;
public
static
final
String west =
"WEST"
;
}
public
class
MainClass
{
public
static
void
main(String[] args)
{
System.out.println(ConstantsWithoutEnums.north);
System.out.println(ConstantsWithoutEnums.south);
System.out.println(ConstantsWithoutEnums.east);
System.out.println(ConstantsWithoutEnums.west);
}
}
New Version:
enum Directions { NORTH, SOUTH, EAST, WEST; } public class EnumsExample { public static void main(String[] args) { Directions d2 = Directions.NORTH; System.out.println(d2); System.out.println(Directions.SOUTH);
System.out.println(Directions.WEST); } }
Output:
NORTH SOUTH EAST WEST
|
No comments:
Post a Comment