Using the Java Enum Type

Instead of using for example static int variables to represent different values in a common category,
Java implements the Enum type which creates a class that contains a list of all its allowed instances.
Other than what is defined within the enum, no other instances are allowed.

An example of Java Enum:

This defines a separate group of enumerated elements (choices).
The beauty of this is that the Color values cannot be mixed with or confused with another type.
Each enum is treated as if it were a different class. Java Enums can contain functionality too, like in this example:

In this example we implement a getColor method in the Fruit enum.
This method can only be called by passing a Fruit as argument. You cannot pass any other value like an int value for example, only Fruit is valid.
In the switch statment there’s no case statement for APPLE since an APPLE can come in many different colors, so if the parameter is an APPLE or any other Fruit that might not be handled in the switch statement, the ANY enum is returned.

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?