I just noticed that the Enum#toString
javadoc states (emphasis mine):
Returns the name of this enum constant, as contained in the declaration. This method may be overridden, though it typically isn't necessary or desirable. An enum type should override this method when a more "programmer-friendly" string form exists.
By default, toString()
and name()
return the same thing, so even once toString
has been overriden, one can still access the name of the enum through the name()
method.
Does anybody know why overriding Enum#toString
would not be desirable?
EDIT: For reference, name()
's javadoc (emphasis as in the original):
Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.
You cannot override enums, and C# does not support return type covariance.
We can declare abstract methods in java enum, then all the enum fields must implement the abstract method. In above example getDetail() is the abstract method and all the enum fields have implemented it. We can define a method in enum and enum fields can override them too.
The equals() method of Enum class overrides the equals() method of class Object.
The static valueOf() method is already defined for us by the Java language, so we can't provide our own valueOf() implementation. Similarly, because the Enum.name() method is final, we can't override it either.
With an enum, you have a specific set of constant values. When the toString
method is called for that enum, one would typically expect the name to be returned, so overwriting the toString
method would return somewhat unexpected results.
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