开发者

Why should I implement toString method for my Object?

Besides printing stuffs for the console what other use have you found for toString() method f开发者_运维知识库or your objects?


It makes a convenient debugging aid when you just want to have a quick look at the contents of an object.


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.


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜