Why is it that when I define an enum, I pass it a list of field names, and then somehow those field names (e.g. Days.MONDAY) end up referring to field values? I can pass along a field (e.g. Days.MONDAY) and then use a switch to get the field value. Even more strange, when I declare the enum fields, I don’t even have to put the names in quotes, even though they are actually values.
Share
Think of the Java enum as a nice syntax for defining a class. Here is a shell transcript that might help:
So yes, you can say
EASTis a field of the classDirectionand its value is an instance of classDirection. We refer to this value asDirection.EASTthe same way you refer to a value through a static field of any other class.Perhaps the confusion is a result of the fact that you don’t see a declaration like
This is understandable. Enums are designed to initialize these field values, but you don’t have to explicitly initialize them yourself. It is as if you said
which is, as a matter of fact, a part of what is called the “Typesafe Enum” pattern which was commonly used before Java got the current enum syntax.
Regarding your comment about quotes, there is simply no reason to have to quote anything, because there are no strings involved.
Regarding your comment about switches, yes, it is somewhat interesting how the notion of field name and field value play out here. But that is only because the value looks like the field. In other words, the value of field
EASTinDirectionis, well,Direction.EAST. If you think about it, though, it is not too different from literals. What is the value ofFloat.NaNyou may ask? Well, it is….Float.NaN. Kind of an opaque value.