Thursday, November 15, 2012

Java Enums - Pointers


Enum keyword is introduced in java 1.5 and became one of the important feature of the language. Its been introduced to represent the fixed number of well know values in java like days of week, months of year etc. How this was handle prior to java 1.5 is explained here. One of the primary reason for adding enum is type safety.

Some of the important features of enum are listed below -
  1. are type safe - can not assign any value other than defined in enum constants
  2. can be used as reference type like class/interfaces- can define constructors, methods and variables inside enums.
  3. specify values of enum constant at creation time 
  4. constructor of enum must be private - otherwise compilation error
  5. constants are implicitly Static and Final - cannot be changed once created
  6. can be used as argument in Switch Statement
  7. can be compared using == equality operator (since enum constants are final)
  8. compiler automatically generates values() method for all enums - returns array of eum constants in the same order as they are listed in enum
  9. can override methods
  10. two new classes EnumMap and EnumSet are added to support the enums
  11. can not create instance of enum using new operator
  12. instance of enum is created when any enum constants are first called or referenced in code
  13. can implement Interfaces and overiride methods like regular java classes
  14. implicitly implements Serializable and Comparable interfaces
  15. can define abstract methods and provide different implementation for different instances of enum

No comments: