Why does javac add values()
and valueOf(String)
methods to the enum type being defined? Wouldn't it have been better that they were added to Enum class itself?
What I mean is, if I have some enum such as
enum FooEnum {ONE, TWO}
javac adds values()
and valueOf(String)
to FooEnum
when compiling it. I find it a bit odd. What is the reason behind this?
Is it only to ensure type safety of the returned value/values or is there anything else? And if it's for type safety alone, wouldn't Generics have helped?
This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type. The values function simply list all values of the enumeration.
valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.
Given those limitations, the enum value alone is not suitable for human-readable strings or non-string values. In this tutorial, we'll use the enum features as a Java class to attach the values we want.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
They're static methods - how could they have been added to Enum
? Static methods aren't polymorphic. Additionally, what would the implementation have looked like in Enum
, in your proposed scheme? Enum
itself doesn't know the values - only the concrete type does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With