• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why enum keyword in Java 5?  RSS feed

 
Landon Blake
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks,

Landon
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This article may get you started.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!