I am getting confused regarding Enum
.
Where and how to use Enum
?
If I will use Enum
instead of constant
then what could be the benefit?
Could someone please explain to me?
I am getting confused regarding Enum
.
Where and how to use Enum
?
If I will use Enum
instead of constant
then what could be the benefit?
Could someone please explain to me?
The primary advantage is type safety. With a set of constants, any value of the same intrinsic type could be used, introducing errors. With an enum only the applicable values can be used.
An Enum class is used to specify a range of constants that will be frequently used within an application.
From http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html:
You should use enum types any time you need to represent a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
A constant class (assuming this is what you are talking about), is really specified for one solid object that you wouldn't change. Technically, an Enum class is a constant class with more definitions, but an advantage to an Enum class is some pre-defined functions that you would have to define in your own constant class. However, you should also note that this may be overkill for small, singleton examples.
Additionally, Enum classes are type-safe, whereas static fields aren't. Compile time error checking is now possible, versus the run-time potential errors that will occur with a constant class. This furthermore improves readability, because instead of having errors where an index of a list of constants is unavailable. This is all well explained in this post, by the current best answer.
As of Java 8.0 the keyword "constant" does not exist.
If you mean "const": This keyword is in the known keywords in Java (from the beginning until today - 8.0), but it has no use and any compiler shouldn't compile if it find's this keyword.
Enumerations: Use them when you have specific logical values and don't want to handle them in String, like:
public enum AcceptableColours {
BLACK,
WHITE,
GREY
}
It's much safer during development time to match enum values
AcceptableColours currentColour = object.getColour;
if (currentColour == acceptableColours.BLACK) {
// do something
} else if (currentColour == acceptableColours.WHITE) {
// do something different
}
than to match string values
AcceptableColours currentColor = object.getColour;
if (currentColor.equals("black")) {
// do something
} else if (currentColor.equals("white")) {
// do something different
}
... imagine huge applications with much more variations on enum values (like banking software, insurance software, ...), where it's much easier to misspell some string values, and voilà, happy debugging...