Thursday, March 27, 2008

JDK 5 enum

Enumerated Types

Let's kick this one off with a quick look at the way we used to simulate enumerated types:

class FizzyDrink {
 static final int PEPSI = 1;
 static final int COKE = 2;
 static final int SCHWEPPES = 3
}

What's the problem here? We now have 3 FizzyDrink types: FizzyDrink.PEPSI, FizzyDrink.COKE, and FizzyDrink.SCHWEPPES, right? Well, not really. We actually just have 3 int values. Take a look at the following code:

int todaysFizzyDrink = 237; // ouch, this shouldn't happen!

This approach is type-unsafe, which means the compiler isn't able to force users of our class to use one of the acceptable values we've defined. Furthermore, because constants are compiled into each class that uses them, this approach can sometimes lead to subtle bugs in code -- you have to remember to track down and recompile every other dependant class each time you need change the class that contains your constants!

Here's the new way:

enum FizzyDrink { pepsi, coke, schweppes }

Notice the use of the enum keyword in place of the class keyword? An enum is really just a special kind of class. Here's an example of this enum in use:

FizzyDrink todaysFizzyDrink = FizzyDrink.pepsi;

Now, we really do have a FizzyDrink type. In fact, if we printed the value of todaysFizzyDrink, we'd get the string pepsi and not some meaningless integer value. Here's the really cool part: no dependant class recompilation is required, and Java will even warn you when you change an enumerated type but still have code elsewhere that uses the old enumerated values!

 

 

 

No comments:

Post a Comment