Some points about Enumerated type in java :
Enums
- Enums were introduced as new type in java in jdk1.5. prior to that there was concept of classes and interfaces(as type) only. But these were not sufficient when we need to define a finite set of allowed values for a specific data type. So enumerated type concept was introduced and it was known by the name enum.
- Enums allow you to dump most of your "public static final" variable declarations.
- Enums are type, like class : As a result, we get type-safety, compile-time checking, and the ability to use them in variable declarations. This overcome the problems that we have faced while using public static final integer or String constant.
- Enums extend java.lang.Enum : java.lang.Enum was a new class in jdk1.5, and is not itself an enumerated type. All enumerated types implicitly extend Enum.
- Enumerated types aren't integers :Each declared value is an instance of the enum class itself; this ensures type-safety and allows for even more compile-time checking.
- Enums have no public constructor :This removes the ability to create additional instances of the enum not defined at compile-time. Only those instances defined by the enum are available. It has only protected constructor.
- Enum values are public, static, and final :Values cannot be overwritten, changed, or otherwise messed with in ways that affect your programming logic. The enum itself is effectively final, as it cannot be subclassed.
- Enum values can be compared with == or equals( ) :Because enums are effectively final, and there is a distinct set of values, you can use—for comparison. Additionally, enumerated types have a working equals( ), for use in collection classes.
- Enums implements java.lang.Comparable :As a result, enum values can be compared with compareTo( ), and ordering occurs in the same order as values are declared in the enum declaration.
- Enums override toString( ) :The toString( ) method on an enumerated type returns the name of the value.
- Enums provide a valueOf( ) method :The static valueOf( ) method complements toString( ). If you change the behavior of toString( ), you need to also change the behavior of valueOf( ). These two methods should always be mirror images of each other.
- Enums define a final instance method named ordinal( ) :oridinal( ) returns the integer position of each enumerated value, starting at zero, based on the declaration order in the enum. Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such java.util.EnumSet and java.util.EnumMap
- Enums define a values( ) method : values( ) allows for iteration over the values of an enum.
I am looking for am good enum explanations from last 6 months. This post is exellent . Thanks a lot :-)
ReplyDelete