
|
|
|||
Getting Started with Enumerated TypesBy Brett McLaughlin2005-04-22
Represent Constants in a Typesafe Manner Using Java 5.0 One of the great new features in Tiger is the enumeration construct, a new type that allows you to represent specific pieces of data as constants, all in a type-safe manner. Tiger expert and frequent developerWorks contributor Brett McLaughlin explains what an enumeration is, how you can use it in your programs, and why it will allow you to dump all that old public static final code. You already know that the two fundamental building blocks of Java code are classes and interfaces. Now Tiger has introduced one more: the enumeration. Usually referred to simply as an enum, this new type allows you to represent specific data points that accept only certain sets of pre-defined values at assignment time. Of course, well-practiced programmers already know you can achieve this functionality with static constants, as shown in Listing 1: Listing 1. Public static final constants public class OldGrade {
Note: I'd like to thank O'Reilly Media, Inc., which has permitted me to use the code sample from the "Enumerations" chapter of my book Java 1.5 Tiger: A Developer's Notebook for this article (see Resources).
You can then set up classes to take in constants like OldGrade.B, but when doing so keep in mind that such constants are Java ints, which means the method will accept any int, even if it doesn't correspond to a specific grade defined in OldGrade. Therefore, you'll need to check for upper and lower bounds, and probably include an IllegalArgumentException if an invalid value appears. Also, if another grade is eventually added (for example, OldGrade.WITHDREW_PASSING), you'll have to change the upper bound on all your code to allow for this new value. In other words, while using classes with integer constants like this might be a passable solution, it's not a very efficient one. Fortunately, enumerations offer a better way. Tutorial Pages: » Represent Constants in a Typesafe Manner Using Java 5.0 » Defining an Enum » Working with Enumerated Values » Enums and Collections » Going Further » Use Them, But Don't Abuse Them » Resources First published by IBM developerWorks |
||||
| About the NetVisits, Inc Network | Write For Us | Advertise Copyright ©2007 NetVisits, Inc Network. All Rights Reserved. Privacy Policy. |
Visit other NetVisits, Inc. sites: |