When to use enums, and when to replace them with a class with static members?

后端 未结 6 1057
情话喂你
情话喂你 2020-11-29 02:16

It recently occured to me that the following (sample) enumeration...

enum Color
{
    Red,
    Green,
    Yellow,
    Blue
}

... could be r

6条回答
  •  执笔经年
    2020-11-29 02:19

    Yup, the original edition of "Effective Java" by Joshua Bloch, which was released prior to Java 1.5 and native support for enums in Java, demonstrated the Typesafe Enum pattern. Unfortunately, the latest release of the book targets Java > 1.5, so it uses Java enums instead.

    Second, you can't cast from int to enum in Java.

    Color nonsenseColor = (Color)17; // compile-error
    

    I can't speak for other languages though.

提交回复
热议问题