Overriding Enum # toString is undesirable?

I just noticed that Enum#toString javadoc claims (my accent):

Returns the name of this enum constant contained in the declaration. This method can be overridden, although this is usually not or desirable . The type of enumeration should override this method when there is a more rigorous form of "programmer".

By default, toString() and name() return the same thing, so even once toString been redefined, you can still access the enumeration name using the name() method.

Does anyone know why overriding Enum#toString undesirable?

EDIT: for reference, name() javadoc (selection as in the original):

Returns the name of this enumeration constant, exactly as specified in the enumeration declaration. Most programmers should use the toString () method, preferring this, since the toString method can return a more convenient name . This method is primarily intended for use in specialized situations where the correctness depends on obtaining an exact name that will not differ from release to release.

+6
source share
3 answers

I think there is simply confusion as to the meaning of the word β€œdesirable” here. Javadoc basically says the same thing twice: overriding toString () is usually not required for the enumeration to work, and therefore it is not useful (desirable) to do this.

So, to answer your question: it would be advisable not to override toString () if: A) you know that you never have to display a string representation of an enumeration name, or B) a standard string representation is enough to define an enumeration if necessary.

+1
source

With an enumeration, you have a specific set of constant values. When the toString method is called for this enumeration, it is usually expected that the name will be returned, so rewriting the toString method will produce some unexpected results.

+3
source

If your listings are more complex than their names, for example. if they contain private fields, toSting() can be overridden to print them and give a better explanation of the enumeration field than just its name.

+2
source

Source: https://habr.com/ru/post/917200/


All Articles