Enums in Java are now defined as special case/implementation for type CLASS. 1.5 Onwards Java empowered enums with some real good features to make it more meaningful and flexible .. but doing so one thing was seen that it enum became more or less CLASS construct... All things which are possible in Enum are more or less found to be easility migratable to Class Contruct... this has coined couple of doubts in my mind...
1. what is distinguishing characteristic of Enum fron ordinary classes. I mean is there anything which can be done ONLY in enum but NOT in class OR VICE-VERSA.
2. Which one should be used when? How one should take a call that I should leverage Enum contruct than the general CLASS construct
Thanks in advance.
“The difference between 'involvement' and 'commitment' is like an eggs-and-ham breakfast: the chicken was 'involved' - the pig was 'committed'.”
K Abhijit wrote:1. what is distinguishing characteristic of Enum fron ordinary classes. I mean is there anything which can be done ONLY in enum but NOT in class OR VICE-VERSA.
Being able to use them in a switch. That's it. All of the rest can be achieved by using a regular class with private constructor and public static final fields; properly implementing the readResolve method will guarantee your instances will not be duplicated when serializing.
2. Which one should be used when? How one should take a call that I should leverage Enum contruct than the general CLASS construct
Enums could (should?) be used when:
- you do not need to extend a class (enums cannot extend a class; implementing interfaces is not a problem)
- your enum does not need to be extended (enums are final)
- you have a fixed set of values that does not need to change during runtime
(there are probably a few more items but I can't think of any right now)