Besides printing stuffs for the console what other use have you found for toString() method for your objects?
It makes a convenient debugging aid when you just want to have a quick look at the contents of an object.
Lots of frameworks use it to provide default representations of your objects, e.g., labels for elements of a tree in Swing.
Besides, just having something readable on the console is enough, because logging is FAR easier when you can rely on the toString()
.
I use it only for debugging purpose. For functional requirements I always implement a well named method like String toExportFormat()
.
You will understand why I do so the first time you try to figure out where your output method is getting called. If you use toString()
somewhere in your code, you will hardly be able to find all places, because each and every object implements this method. If you use a specialized method, it's very easy to find the places where it is called. And you can refer to this method inside your toString()
method - it's not even more work.