Read Also : Difference between EnumMap and HashMap
1. What Is Enum ?
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.1.1 EXAMPLE :
With the following simple declaration,
enum Direction
{
NORTH,SOUTH,EAST,WEST;
}
you can guarantee that the compiler will stop you from assigning anything to a Direction except NORTH,SOUTH,EAST,WEST.
If you let a Direction such as NORTH-WEST, NORTH-EAST slip in the code without defining in the Direction enum, it might cause an compiler error.
2. When To Use Enum
You should use enum types any time you need to represent a fixed set of constants. The value of the fixed constants known at the compile time.
3. Declaration of Enum in java:
Enums can be declared outside the class or inside the class however they must not be declared inside the method.3.1 Declaring an enum outside a class:
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
public class EnumOutsideClass {
public static void main(String args[])
{
Direction dir = Direction.NORTH;
System.out.println(dir);
}
}
Output :
NORTH
Remember that file must be named EnumOutsideClass.java because that's the name of the public class in the file.
3.2 Declaring an enum inside a class :
// Declaration : enum inside a class.
public class EnumInsideClass
{
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
public static void main(String[] args)
{
Direction dir = Direction.SOUTH;
System.out.println(dir);
}
}
Output :
SOUTH
3.3 ILLEGAL : Declaring an enum inside a method
public class EnumInsideMethod
{
public static void main(String[] args)
{
// Declaration : enum inside a method.
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
Direction dir = Direction.SOUTH;
System.out.println(dir);
}
}
Output:
/EnumInsideMethod.java:6: error: enum types must not be local
enum Direction {
^
1 error
As you can see above, java program throws compiler error when we declare an enum inside a method.
4. How Enum Internally Represented?
The most important point to remember is that enums are not Strings or ints. Each of the Direction constants(enum types) are actually instances of Direction. In other words, NORTH is of type Direction. Think of an enum as a kind of class, that looks something (but not exactly) like this:class Direction extends Enum {
public static final Direction NORTH = new Direction();
public static final Direction SOUTH = new Direction();
public static final Direction EAST = new Direction();
public static final Direction WEST = new Direction();
}
Every enum constant is always by default public static final. Since it is static, we can access it by using enum name. It is final, because the constants value should not be changed.
5. Enum ordinal(),values() and valueOf() methods with Example
5.1 ordinal() method example
ordinal() returns its position in the enum declaration, where the initial constant is assigned an ordinal of zero. It is similar to Array indexes. Each enum index can be found using ordinal() method.
// An Enum
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
// Java program demonstrates ordinal() example
public class EnumOrdinalExample
{
public static void main(String[] args)
{
int pos = Direction.NORTH.ordinal();
System.out.println("NORTH ordinal : "+ pos);
int pos1 = Direction.SOUTH.ordinal();
System.out.println("SOUTH ordinal : "+ pos1);
int pos2 = Direction.EAST.ordinal();
System.out.println("EAST ordinal : "+ pos2);
int pos3 = Direction.WEST.ordinal();
System.out.println("WEST ordinal : "+ pos3);
}
}
Output :
NORTH ordinal : 0
SOUTH ordinal : 1
EAST ordinal : 2
WEST ordinal : 3
5.2 values() method example
static values() method returns an array containing all of the values of the enum in the order they are declared. This method is used for enum iteration.
// An Enum
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
// Java program demonstrates values() example
public class EnumSwitchExample
{
public static void main(String[] args)
{
Direction[] dir = Direction.values();
for (Direction d : dir) {
System.out.println(d);
}
}
}
Output :
NORTH
SOUTH
EAST
WEST
5.3 valueOf() method example
it helps to convert String to enum instance.
// An Enum
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
// Java program demonstrates valueOf() example
public class EnumSwitchExample
{
public static void main(String[] args)
{
Direction north = Direction.valueOf("NORTH");
System.out.println(north);
}
}
Output :
NORTH
6. Enum and switch Statements example
Enum type can be passed as an argument to the switch statement as shown in below example.
//Enum switch Statements example
// An Enum
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
public class EnumSwitchExample
{
Direction dir;
// Constructor
public EnumSwitchExample(Direction dir)
{
this.dir = dir;
}
public void directionMoving()
{
switch (dir)
{
case NORTH:
System.out.println("Moving North");
break;
case SOUTH:
System.out.println("Moving South");
break;
case EAST:
System.out.println("Moving East");
break;
case WEST:
System.out.println("Moving West");
break;
default:
System.out.println("Keep Moving");
break;
}
}
public static void main(String[] args)
{
String str = "EAST";
EnumSwitchExample obj = new EnumSwitchExample(Direction.valueOf(str));
obj.directionMoving();
}
}
OUTPUT :
Moving East
7. Enum Methods
Just like any other class, enum can have methods and fields. You can add abstract methods and non-abstract(concrete) methods to the enum.7.1 Adding concrete (non-abstract) methods to Enum Example
As we have already discussed, you can add concrete method to the enum. Non-abstract method can have any access specifier(private, public, protected, default). You can write any logic inside concrete method and it can return any value just like methods do in any other class.
enum Direction
{
NORTH, SOUTH, EAST, WEST;
public String showDirection()
{
String movingDir = "Moving " + this + " direction";
System.out.println( movingDir );
return movingDir;
}
}
public class EnumMethodExample {
public static void main (String args[])
{
Direction.NORTH.showDirection();
}
}
Output :
Moving NORTH direction
7.2 Adding abstract method to Enum Example
An enum can contain abstract methods too. If enum has an abstract method, then each of the enum instances(enum constants) need to implement the abstract method.
enum Direction
{
// enum constants
NORTH {
@Override
public String showDirection() {
return NORTH.toString();
}
},
SOUTH {
@Override
public String showDirection() {
return SOUTH.toString();
}
},
EAST {
@Override
public String showDirection() {
return EAST.toString();
}
},
WEST {
@Override
public String showDirection() {
return WEST.toString();
}
};
public abstract String showDirection();
}
public class EnumAbstractMethodExample {
public static void main (String args[])
{
String movingDir = Direction.NORTH.showDirection();
System.out.println(movingDir);
}
}
Output :
NORTH
8. Why Enum are Singleton
clone method in Enum class is final, hence, it ensures that the enum constants are never be cloned. The special treatment by Serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Thus, above things ensure that no instances of an enum type exist beyond those defined by the enum constants.9. Compare Enums
Since enum are singletons by default. It is permissible to use the == operator in place of equals() method when comparing two object references if it is known that at least one of them refers to an enum constant.So, you can compare enums with equals() method as well as == operator.
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
public class EnumCompareExample {
public static void main (String args[])
{
Direction south = Direction.SOUTH;
Direction southObj = Direction.valueOf("SOUTH");
System.out.println( south == southObj );
System.out.println( south.equals( southObj ) );
}
}
Output :
true
true
10. Enum and Constructors
Enum do not require constructors. Although, you can define your own constructor to initialize the state of the enum.Enum constructor must have either private or default scope. You can not use public or protected scope for the enum constructor.
11. EnumSet
Java contains a class which is a special implementation of Set called EnumSet. It can hold enums more efficiently than standard java Set implementation. Below is the example of how to create EnumSet object.import java.util.*;
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
public class EnumSetExample {
public static void main (String args[])
{
EnumSet<Direction> enumSet = EnumSet.of(Direction.NORTH,
Direction.SOUTH,
Direction.EAST,
Direction.WEST);
}
}
12. EnumMap
Java contains a class which is a special implementation of Map called EnumMap. It uses keys as java enum instances. Below is the example of how to create EnumMap object.import java.util.*;
enum Direction
{
NORTH, SOUTH, EAST, WEST;
}
public class EnumMapExample {
public static void main (String args[])
{
//Keys can be only enum type, in our case, Direction
EnumMap<Direction, String> enumMap = new EnumMap<Direction, String>(Direction.class);
//Inserting key value pairs in EnumMap object
enumMap.put(Direction.NORTH, "NORTH");
enumMap.put(Direction.SOUTH, "SOUTH");
enumMap.put(Direction.EAST, "EAST");
enumMap.put(Direction.WEST, "WEST");
}
}
13. Naming Convention
The name of the enum should be camelCase. Enum constants should be in all uppercase as they are static final constants.Enum constants need not to be in capital letters. But borrowing from the Sun code convention and a good practice that constants are named in capital letters.14. Difference between Enum and Class
1. By default enum constants in java are public,static and final (i.e they can not be overridden).2. An enum can not be used to create objects while Class can be used to create objects.
3. An enum can not extend other classes while Class can extend only one other class.
15. Points To Remember
1. enum constants are implicitly static final. Value can not be changed once assigned.2. Using == operator or equals() method is same for comparing enum constants.
3. All enums implicitly extend java.lang.Enum. Enum class is an abstract class. Enums can not extend any other class as java does not support multiple inheritance.
4. Enum in java are type-safe.
5. Instance of the enum can not be created by using new operator.
6. enums are by default singleton.
7. Enums provide their namespace.
8. An enum can be declared inside the class, outside the class but not inside a method.
9. An enum declared outside the class must NOT be marked abstract, static, final, private or protected.
10. You can use enum in switch statement just like int or char primitive data type.
11. If enum contains no methods and fields then putting the semi colon at the end of declaration is optional. Otherwise, it is mandatory.
l2. enum is a reserved keyword in java.
In this article we explored almost everything about enum in java. If you have any questions regarding java enum or enum example then please mention in comments.
References : Oracle docs
0 Comments