While Java 5 is no longer considered "new," I would guess that many of the features introduced with the version are still "new" or underutilized by most developers. In this entry we'll take a look at the "new" Enum. So what is so great about the new Enum? For starters, it's an object... well kinda... it's a Java object; inconsistent semi-OO quirks and all.
An Enum instance is technically an instanceof java.lang.Object, but when creating a new Enum you don't declare a new class, you use the enum keyword. I hear the (non-existent) reader asking, "that's pretty basic stuff... what's the big deal?" The big deal is that unlike traditional uses of an Enum as a grouping of constant values, the Java 5 Enum is a grouping of constant instances that have properties and behavior. Every instance is statically defined at design time, but that doesn't prevent it from providing behavior to interact with other dynamic objects at runtime.
Let's have a look at an example:
Every MenuItem instance has two properties and one behavior-defining method; private String displayName, private Double price, and public Double calculateSalePrice( Double salesTaxRate ) (respectively).
We'll focus on the DOUBLE_CHEESE_MEAL instance... you'll note that it's declaration provides it's own overridden implementation of getPrice() that doesn't just return a constant property value, but instead returns a calculated value based on the price of it's contents (a "Double McCheesy Meal Deal" - two "McCheesy" cheeseburgers, one "McFrench Frie", and one "McSoft Drink"). You'll want to note that the calculateSalePrice(...) method makes use of getPrice() so the DOUBLE_CHEESE_MEAL instance will calculate it's sale price against it's own calculated price.
To finish this longer than necessary post to explain a little with a lot, I'll add that any Java 5 Enum instance that provides it's own methods (ie DOUBLE_CHEESE_MEAL), is compiled like a standard inner class. For example, MenuItem.java compiles to MenuItem.class and MenuItem$1.class. If there were more than one declared MenuItem with it's own overrides, then MenuItem$2.class would exist after compilation.
The sample code and eclipse project can be downloaded in it's entirety here.