Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Enum#toString not desirable?

Tags:

java

enums

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.

like image 346
assylias Avatar asked Jun 01 '12 15:06

assylias


People also ask

Can I override an enum?

You cannot override enums, and C# does not support return type covariance.

Can we override enum in Java?

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.

Can we override equals method in enum?

The equals() method of Enum class overrides the equals() method of class Object.

Can I override valueOf enum Java?

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.


1 Answers

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.

like image 146
Seth Avatar answered Sep 18 '22 15:09

Seth