JavaData & JavaLearn Enumeration in Java

Learn Enumeration in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Enumeration is a recent (from JDK5) inclusion into the family of Java APIs. It basically represents a list of named constants. Apart from Java, almost all other prominent programming languages have the feature of enumeration. Although Java has the final keyword to represent constants, enumeration was included as a convenience to meet many of the streamlined needs of the programmer. This article tries to provide the background information and show how enumerations can be utilized in Java.

Overview of Java Enumerations

Unlike the features of enumeration in other languages, the enumeration designated by the keyword enum in Java represents a special type of class. This inherent capability bolstered the principle of expansion in Java. Because it is a class type, it has a constructor, methods, and instance variables associated with it.

The values defined by the enum are constant. This means they are implicitly static and final. It is not possible to change the values after declaration. The enum is ideally used to represent a set of fixed named constants. For example, to enumerate a list of gender varieties, we may write:

enum Gender{ Male, Female, Third }

The identifiers Male, Female, and Third are called enumeration constants. As stated earlier, they are by default public static and final members of the enum class. These constants declared are of self typed. We can declare a enum variable as

Gender gender;

and can assign a value as

gender=Gender.Male;

We also can use a comparison operator as such:

if(gender!=Gender.Female) // ...

Or, use it with the switch statements, as in this example:

switch(gender){
   case Male:
      // ...
   case Female:
      // ...
   case Third:
      // ...
}

Observe that we have not used any qualifier, such as Gender.Male, with the case statement; instead, we used only the named constant Male. This is possible because, when we have declared gender with the switch, statement it implicitly recognizes the type of the enum constants.

Use of values() and valueOf () Methods

We can specify custom values with enum constants at the time of declaration. In the following code, we have specified some values. But, to actualize this principle, we must declare a private member variable and a private constructor.

enum Gender {
   Male(1), Female(2), Third(3);
   private int value;

   private Gender(int value) {
      this.value = value;
   }
   public int getGender() {
      return value;
   }
}

Because the Enum class implements the Comparable interface, the use of compareTo() is its inherent capability. Moreover, the Java compiler automatically creates a static method, called values(), which returns an array of named constants defined in the enum. There is another static method, called valueOf(), which takes enum class types and the named constant in the string format. This method returns the enumeration constant of the value that corresponds to the string passed in the parameter. We can use them in the following manner:

Gender gender;
for(Gender g: Gender.values()){
   System.out.println(Gender.valueOf
      (Gender.class, g.name())
      +" "+g.getGender());
}

Java Enumeration as a Class

Although Java enumeration is of the class type, we do not use the new keyword to instantiate it. The association of a class as its principle design gives it some extraordinary capability. It can be used like any other normal classes in Java. We can declare a constructor, define member variables and methods, and even implement an interface. When we create an enumeration constant, an object of that type actually is created. When the constructor is invoked, the enumeration constants are initialized. This also means that each enumeration object has its own copy of its member variables defined by it. Therefore, it can be said that following two enumeration declarations are quite distinct.

Gender g1;
Gender g2;

Inheritance

An enum class can inherit from a super class or implement a super interface. Following is a perfectly valid declaration:

public class SuperClass // ...

public interface SuperInterface // ...

public class EnumDemo extends SuperClass
   implements SuperInterface // ...

However, all enumeration classes automatically inherit java.lang.Enum. As a result, the methods declared in java.lang.Enum are all available to the enum delaration.

public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable

The java.lang.Enum does not have a public constructor. The method declared in this class is compareTo() due to the implementation of the Comparable interface, clone(), hashCode(), toString(), and equals() due to the inheritance of the Object class. Other member methods declared are as follows:

  • final String name(): Returns the name of the enum constant
  • final int ordinal(): Returns the value that indicates the position of the enumeration constants
  • static <T extends Enum<T>> T valueOf(): Returns the constant associated with the name
  • final Class<E> getDeclaringClass(): Returns the class associated with the enumeration constant

A Quick Java Enumeration Example

public enum Zodiac {
   ARIES, TAURUS, GEMINI, CANCER, LEO, VIRGO, LIBRA,
   SCORPIO, SAGITTARIUS, CAPRICORN, AQUARIUS, PISCES
}

public class EnumDemo{

   public static void main(String[] args) {

      for(Zodiac z: Zodiac.values()){
         System.out.println(z.ordinal());
      }

      Zodiac z2=Zodiac.SAGGITARIUS;
      Zodiac z3=Zodiac.GEMINI;
      if(z2.compareTo(z3)==0)
         System.out.println(z3+" same as "+z2);
      else if(z2.compareTo(z3)<0)
         System.out.println(z3+" comes after "+z2);
      else
         System.out.println(z3+" comes before "+z2);
   }
}

Output:

0
1
...
11
GEMINI comes before SAGITTARIUS

Abstract Method in enum

It is possible to define an abstract class within enum as follows:

package org.mano.example;

public enum Zodiac {
   ARIES{
      @Override
      public String toString(){
         return "I mean action, think later";
      }
   }, TAURUS{
      @Override
      public String toString(){
         return "Pull me up, I'll show what am capable of";
      }
   }, GEMINI{
      @Override
      public String toString(){
         return "I always think about what to think";
      }
   }, CANCER{
      @Override
      public String toString(){
         return "I pile up emotions until they bite";
      }
   }, LEO{
      @Override
      public String toString(){
         return "Look at me and bow";
      }
   }, VIRGO{
      @Override
      public String toString(){
         return "I hate loose talks";
      }
   }, LIBRA{
      @Override
      public String toString(){
         return "Everything gets out of my control";
      }
   }, SCORPIO{
      @Override
      public String toString(){
         return "I dwell in the dark secrets";
      }
   }, SAGITTARIUS{
      @Override
      public String toString(){
         return "I'll act only when I'm sure";
      }
   }, CAPRICORN{
      @Override
      public String toString(){
         return "Life is full of empty dreams";
      }
   }, AQUARIUS{
      @Override
      public String toString(){
         return "World is just a village";
      }
   }, PISCES{
      @Override
      public String toString(){
         return "Catch me, if you can";
      }
   };

   public abstract String toString();
}

package org.mano.example;

import java.util.EnumMap;

public class EnumDemo {

   public static void main(String[] args) {
      EnumMap<Zodiac, String> zodMap =
         new EnumMap<>(Zodiac.class);
      for(Zodiac z:Zodiac.values()){

         zodMap.put(Zodiac.valueOf(z.name()), z.toString());
      }

      for(Zodiac zz:zodMap.keySet()){
         System.out.println(zz.name()+": "+zz.toString());
      }
   }
}

Conclusion

Enumeration can be used in many ways. What you’ve seen here is another versatile feature of Java. This capability can be worked up to use according to the need of the programmer. The idea is to treat enumeration like a special class that defines a list of named constants. So, without using several final static variables to declare a collection of constants, we can use enumeration. The goal is to provide readability, conceptual purity, and ease of use.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories