Thursday, July 16, 2009

Enums in Java 5

Following are the advantages of using Enums:

  • Enums are type safe.
  • Enums are Serializable and Comparable by default
  • Programmers doesn’t require to do extra work of implementing toString(), equals() and hashCode(). Enums provide implementation of these by default.
  • Programmers can use Enums in switch-case statements.
  • Enums are permitted to implement to interfaces.

Java 5.0 lets you to confine a variable to have only a fixed set of predefined values. For example, a cold drink shop may want to serve cold drinks in just three sizes- SMALL, MEDIUM, and LARGE. With this simple declaration, it can be guaranteed that the compiler will stop you from assigning anything to cold drinks except SMALL, MEDIUM, and LARGE.

Syntax enum DrinkSize {SMALL, MEDIUM, LARGE};

Now, if you want to get DrinkSize, you will do something like this

DrinkSize ds = DrinkSize.SMALL;

According to sun coding convention, all constants should be in caps, although you can give these in small letters also.

One important rule you need to remember about Enums is:

They must not be declared within a method.

How to declare Enum outside a class?

enum DrinkSize { SMALL, MEDIUM, LARGE } // this cannot be

// private or protected

class Drink {
DrinkSize size;
}
public class DrinkTest {
public static void main(String[] args) {
Drink drink = new Drink ();
drink.size = DrinkSize.BIG; // enum outside class
}
}

Key point to remember here is that the enum can be declared with only public or default modifier.

How to declare Enum inside a class?

class Drink {
enum DrinkSize { SMALL, MEDIUM, LARGE }
DrinkSize size;
}
public class DrinkTest {
public static void main(String[] args) {
Drink drink = new Drink();
drink.size = Drink. DrinkSize.SMALL; // enclosing class
// name required
}
}

At the end of the enum, putting a semicolon is optional

enum DrinkSize { SMALL, MEDIUM, LARGE };

5 comments:

  1. hi there,

    i think you need a little organization of your topic, dont let the user see all the content of the topic at once, let them see the summary first,

    regards
    http://lolotechie.com

    ReplyDelete
  2. Hi Gaurav,

    Enums introduced in JAVA5 seems great, but do you have any idea about its performance as compared to simple constants declared with static final......

    ReplyDelete
  3. Quite informative, indeed Enum are more versatile than one can think of , see the below post 10 examples of enum in java to know what else can you do with enum in java.

    ReplyDelete