Java 5 Enums

From NovaOrdis Knowledge Base
Revision as of 23:32, 20 August 2016 by Ovidiu (talk | contribs)
Jump to navigation Jump to search

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.

When should we use enum?