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 -
- are type safe - can not assign any value other than defined in enum constants
- can be used as reference type like class/interfaces- can define constructors, methods and variables inside enums.
- specify values of enum constant at creation time
- constructor of enum must be private - otherwise compilation error
- constants are implicitly Static and Final - cannot be changed once created
- can be used as argument in Switch Statement
- can be compared using == equality operator (since enum constants are final)
- compiler automatically generates values() method for all enums - returns array of eum constants in the same order as they are listed in enum
- can override methods
- two new classes EnumMap and EnumSet are added to support the enums
- can not create instance of enum using new operator
- instance of enum is created when any enum constants are first called or referenced in code
- can implement Interfaces and overiride methods like regular java classes
- implicitly implements Serializable and Comparable interfaces
- can define abstract methods and provide different implementation for different instances of enum
No comments:
Post a Comment