I know that the Javadocs says:
Returns a string representation of the object. In general, the
toString method returns a string that “textually represents” this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.
But when should I spend time overriding the toString method for my classes? Should it be one of the first things I do along with overriding equals and hashCode? Or should I wait until it’s actually needed?
I know Eclipse can auto generate toString methods for you, so should I just have Eclipse auto generate them once I know the fields for my class?
Josh Bloch gives a good explanation in Effective Java, in item 10.
It really makes it easier to output debugging traces, or makes better logging messages, since you can use the object’s string representation provided by
toString()directly; you don’t have to manually build a string that gives the information needed on the object.As stated in the book, you should include all the interesting information in the resulting
String. You should also document properly your method; you may document the resultingStringformat or not, but you should at least document your intent (whether the format is subject to change, or not likely to change).In the end, it is up to you (and your company’s standards) to decide if overriding it in every class should be part of your habits or not. Personally, I don’t override
toString ()in every classes, only in the ones which are most at risk of being used in a debuging trace.