[JAVA] History of Enum
What is Enum?
An enum type, introduced in Java 5, is a special data type that enables a variable to be a set of predefined constants. It is often used when we know all the possible values at compile time while the set of constants can be modified whenever we need them.
History of Enum
Until the enum type was presented, Java developers used to define constants with extra comments:
In this code, Monday should be fixed at 1, Tuesday at 2, and Wednesday at 3. As this rule is set on a comment, it would be a problem to divide the comment and the code or to delete one of them, especially the comment. We can improve it if we get to know the meaning of the numbers by their own name.
Now each number has its own name that we can easily figure out so that the switch statement becomes more straightforward. Also, the variables become constant by the final
keyword and are assigned only once on memory by the static
keyword. Note that we can better source code in using an interface as this shape of code ( private final static
) can be left out in it:
Looks way better, doesn’t it? Nonetheless, it has one trivial problem, where it cannot guarantee compile-time safety when you try comparing two different sets of constants like:
if (Day.Monday == Month.January) {
System.out.println("Mondays are bad");
}
If the Java compiler doesn't find that kind of source code and doesn’t mark it as an error, you might have an unexpected error in runtime. To get rid of the risk, one smart Java developer might suggest a way to change the interfaces to classes and to make the data type of each constant to neither int nor other things but to its class so that an instance of their class would be assigned to every single of them. If then, it’s certain that the compiler finds the error as Day.Monday
and Month.January
belong to different data types. But one constraint still remains in this amazing method that you cannot use the switch
statement any longer because it does not support customized data types. Boom! Here is the reason why an enum type has been presented from Java 5.
Conclusion
Everything has its own history. Millions of Java developers’ outrages and tons of broken keyboards had been stacked up so long that Sun Microsystems decided to create the enum type. The next post will cover up what it is consisted of and how it works. Thanks for reading.