Java 5 Enums: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 23: | Line 23: | ||
* '''Brittleness''' because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined. | * '''Brittleness''' because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined. | ||
* Printed values are uninformative. | * Printed values are uninformative. | ||
Java 5 added syntactic support for ''enumerated types'': | |||
<pre> | |||
public class Example { | |||
public enum Color { BLUE, RED, WHITE, BLACK }; | |||
.... | |||
} | |||
</pre> | |||
The above declaration defines a ''full-fledged class'', known as ''enum type''. |
Revision as of 23:31, 20 August 2016
Externa
Internal
Overview
The standard way of representing an enumerated type in pre-5 Java was the "int Enum pattern":
public static final int COLOR_RED = 0; public static final int COLOR_BLUE = 1; public static final int COLOR_WHITE = 2; ...
Problems with this approach:
- Not type safe any int value can be passed as a "color". There is no concept of "color" type.
- No namespace you must prefix constants of an int enum with a string (in this case COLOR_) to avoid collisions with other int enum types.
- Brittleness because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
- Printed values are uninformative.
Java 5 added syntactic support for enumerated types:
public class Example { public enum Color { BLUE, RED, WHITE, BLACK }; .... }
The above declaration defines a full-fledged class, known as enum type.