Java enum – why use toString instead of name

If you look in the enum api at the method name() it says that:

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.

Why is better to use toString()? I mean toString may be overridden when name() is already final. So if you use toString and someone overrides it to return a hard-coded value your whole application is down… Also if you look in the sources the toString() method returns exactly and just the name. It’s the same thing.

7 Answers
7

Leave a Comment