I've been learning about the new enum keyword in Java 5. I'm curious what you can accomplish with the new enum keyword that you coudln't accmoplish before with regular Java objects.
For example, you create an Enum class that does the following:
- Contains a Map that associates String keys with Integer values. - Contains a private int that contains the "current" value of the Enum in instances of the Enum class. - Restricts outside access to the Map. - Only allows keys and values to be set in the class when it is constructed. - Throws an exception if someone attempts to set an invalid value as the value of an Enum instance.
I've read that enum keyword gives increased type safety in Java, at least compared to using variables in a class definition, but if you used a class like the one I just described I don't think this is the case. You couldn't ever set an incorrect value in the class described above, and methods could be written to accept instances of the class, not raw ints.
I know the guys (and gals) that design the Java programming language are a lot smarter than me. I must be missing some great advantage of the enum keyword. It just seems odd to add that amount of complexity to the language for something that could be acheived with regular classes.
Can someone explain the design logic/advantages of the enum keyword to me?
Joined: Feb 05, 2003
As more recent changes in Java, it was not strictly necessary to add enums, but merely convenient. The existing solutions were as you indicated not very save (constants), or tedious to implement correctly (classes). Moreover, they do exist in several other languages, so developers are used to have them available. For this readon,it was decided to add them to the language, and then also allow them to be used in switch cases, which can not be done using classes.
Compare for example to the enhanced for loop, also not really necessary, but convenient to have.
Yes, you could do exactly the same things before Java 5 - it was just more work, you simply had to write more code. With other words, it's pure syntactic sugar - quite sweet sugar, I would add.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus