Why is an Enum considered more type-safe than constants?

enums, java, type-safety

Solution

Imagine these two method signatures:

void rawF(char someFlag);

void enumF(MyFlags someFlag);

The latter is more restrictive as only the valid values of `MyFlags` are allowed. In the former case, any character could be passed - even if only the values defined in "constants" where used.

Happy coding.

Problem

In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved type-safety): ``` public class OfficePrinter { public enum PrinterState { Ready, OutOfToner, Offline }; public static final PrinterState STATE = PrinterState.Ready; } static final char MY_A_CONST = 'a'; ```

Original source