Java Tutorial – 20 – Enum

An enumerator is a type that consists of a
fixed list of named constants. To create one we use the enum keyword followed by a name
and then a code block containing a comma separated list of constant elements. We can now define
a variable of this enum type, which can hold any one of these constants. To assign it one
of the constants we just access them from the enum type as if they were static fields
of a class. The switch statement provides a good example
of when it would be useful to have an enumerator. Compared to using ordinary constants the enumerator
has the advantage of allowing us to clearly specify what constant values are allowed.
Note that when using an enum in a switch statement the case labels are not qualified with the
name of the enum. The access level for an enumerator is the
same as for a class. It’s package-private by default but can also be set to public if
it is declared in a file with that same name. Just as with classes an enumerator can also
be contained within a class, where it can be set to any access level. In Java the enum type is more powerful than
its counterparts in other languages. It is essentially a special kind of class and can
include anything that a class can include. If we want to add a class member then the
list of constants must be ended with a semicolon and the member must be declared after the
constants. As an example, we’ll add an integer to the enum that will hold the actual speed
that the elements represents. To set this variable we’ll need to add a constructor
as well. A constructor in an enumerator must have either private or package-private access
and it is not called in the same way as in a class. Instead, the parameters to the constructor
are given after the constant elements. So, if we for example create an enum and assign
it the constant “slow”, then the parameter 5 will be passed to the constructor for this
enum instance. Another difference that enum types have when
compared to classes is that they implicitly extend from the java.lang.Enum class. In addition
to the members inherited from this class, the compiler will also automatically add two
static methods to our enumerator, called values and valueof. Values for example returns an
array of the constant elements declared in the enum.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *