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?
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.
toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.
Overriding toString to be able to print out the object in a readable way when it is later read from the file.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler.
I would implement toString()
method on any class that holds human understandable non confidential data
. Ex: Transfer Object, Beans, Data Object, Wrappers. For such classes just go on to implement 'toString()' method.
Classes that represent a service, process with transient states need not implement the method.Here, You can wait until it is actually needed.
Make sure you do not expose any variables with "transient" keyword in 'toString()'!
Josh Bloch gives a good explanation in Effective Java, in item 10.
[...] providing a good toString implementation makes your class much more pleasant to use.
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 resulting String
format 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.
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