The knowledge sharing zone - Guruzon.com

Use of enum in java

This tutorial contains the details about What is Enum, Use of Enum in your application, When and How to use Enum.
  • Related Topics:
reviews
  • In Java 1.5 (Tiger), One of the new introduced feature is Enums.
  • Java 1.5 lets you restrict a variable to having one of only a few pre-defined values—in other words, one value from an enumerated list. The items in the enumerated list are called Enums.
  • Using enums can help reduce the bugs in your code.

Enum declaration

  • An enum that isn't enclosed in a class can be declared with only the public or default modifier, just like a non-inner class.
  • Enums can be declared as their own class, or enclosed in another class, and that the syntax for accessing an enum's members depends on where the enum was declared.

Enum examples

  • In your coffee shop application you might want to restrict your size selections to BIG, HUGE, and OVERWHELMING. 
  • If you let an order for a LARGE or a GRANDE slip in, it might cause an error. 
  • Enums to the rescue. With the following simple declaration, you can guarantee that the compiler will stop you from assigning anything to a CoffeeSize except:  BIG, HUGE, or OVERWHELMING:
enum CoffeeSize { BIG, HUGE, OVERWHELMING }; // semicolon is optional here in enum

So now the only way to get a CoffeeSize in your statement using something like:

CoffeeSize cs = CoffeeSize.BIG;
  • It is not required that enum constants must be in all caps, but borrowing from the Sun code convention that constants are named in caps, it's just a good idea. 
  • The basic components of an enum are its constants (eg. BIG, HUGE, and OVERWHELMING)
  • Enums can be declared as their own separate class, or as a class member, however they must not be declared within a method.

Example of declaring an enum inside a class:

class Coffee2 {   
    enum CoffeeSize {    
        BIG, HUGE, OVERWHELMING 
    }; // semicolon is optional here
    CoffeeSize size; 
}

public class CoffeeTest2 {   
    public static void main(String[] args) {     
        Coffee2 drink = new Coffee2();     
        drink.size = Coffee2.CoffeeSize.BIG;   // enclosing class              
                                               // name required   
    }
}

The following is NOT legal:

public class CoffeeTest1 {   
    public static void main(String[] args) {     
        enum CoffeeSize { // WRONG! Cannot declare enums in methods
            BIG, HUGE, OVERWHELMING 
        }
        Coffee drink = new Coffee();
        drink.size = CoffeeSize.BIG;
    }
}

Enum internals - What gets created when you make an enum? 

  • The most important thing to remember is that enums are not Strings or ints!
  • Each of the enumerated CoffeeSize types are actually instances of CoffeeSize. For example, BIG is of type CoffeeSize.

You can think of an enum as a kind of class which looks something like this:

// conceptual example of how you can think about enums

class CoffeeSize {
    public static final CoffeeSize BIG = new CoffeeSize("BIG", 0);
    public static final CoffeeSize HUGE = new CoffeeSize("HUGE", 1);
    public static final CoffeeSize OVERWHELMING = new CoffeeSize("OVERWHELMING", 2);

    public CoffeeSize(String enumName, int index) {
        // stuff here     
    }
    public static void main(String[] args) {
        System.out.println(CoffeeSize.BIG);
    }
}

Declaring Constructors, Methods, and Variables in an enum

  • Enum really is a special kind of class and with that you can do more than just list the enumerated constant values.
  • You can add constructors, instance variables and methods.

Why you might need more in your enum?

To understand that, Think about this scenario:

  • Imagine you want to know the actual size, in ounces, that map to each of the three CoffeeSize constants.
  • For example, you want to know that BIG is 8 ounces, HUGE is 10 ounces, and OVERWHELMING is a whopping 16 ounces.
  • You could make some kind of a lookup table and by using some other data structure but that would be a poor design and hard to maintain.
  • The simplest way is to treat your enum values (BIG, HUGE, and OVERWHELMING) as objects that can each have their own instance variables.
  • Then you can assign those values at the time the enums are initialized, by passing a value to the enum constructor.

 

enum CoffeeSize {
    // 8, 10 & 16 are passed to the constructor
    BIG(8), HUGE(10), OVERWHELMING(16);
    CoffeeSize(int ounces) {
        // constructor
        this.ounces = ounces;
    }

    // an instance variable
    private int ounces;

    public int getOunces() {
        return ounces;
    }
}

class Coffee {
    CoffeeSize size; // each instance of Coffee has an enum

    public static void main(String[] args) {
        Coffee drink1 = new Coffee();
        drink1.size = CoffeeSize.BIG;
        
        Coffee drink2 = new Coffee();
        drink2.size = CoffeeSize.OVERWHELMING;
        
        System.out.println(drink1.size.getOunces()); // prints 8
        for (CoffeeSize cs : CoffeeSize.values())
            System.out.println(cs + " " + cs.getOunces());
    }
}

/*
Which produces:
8
BIG 8
HUGE 10
OVERWHELMING 16
*/

Note: Every enum has a static method values() which returns an array of the enum's values in the order they're declared.

You would also like to read:

Comments :


Thanks a lot, It really useful. Now I got more idea of where

up vote icon down vote icon

Thanks a lot, It really useful. Now I got more idea of where and how to use java enum more efficiently.

up vote icon down vote icon

Clearly understood the use of enum now. Thanks a lot.

up vote icon down vote icon
Name :
Email :
Comment :
Verify Text :
capch image, refresh page if not loaded somehow