This article introduces you to the difference between enumerated types and typesafe enums. You will learn how to declare a typesafe enum and use it in a switch statement, and you'll see how to customize a typesafe enum by adding data and behaviors. We'll also take a look at java.lang.Enum<E extends Enum<E>>
, which is the base class for all typesafe enums.
What you'll learn in this Java tutorial
- Why use typesafe enums and not enumerated types
- How to use typesafe enums in switch statements
- How to add data and behaviors to typesafe enums
- Details and examples of the Enum class (Enum<E extends Enum<E>>)
Why use typesafe enums, not enumerated types
An enumerated type specifies a set of related constants as its values. Examples include the days in a week, the standard north/south/east/west compass directions, a currency’s coin denominations, and a lexical analyzer’s token types.