Always Remember to override toString() [Effective Java]

5 10 2013

Default implementation of toString() in Object class is class name, ‘@’ sign and hash code. All of it is not enough when you want to print or debug object state if the class is used by you. Even worse, if your class is used by external developers with API you provide.

How to do it in eclipse?

No – you don’t have to implement it by yourself :) Eclipse is here for help. To override toString() simply:

  • in Eclipse editor right click -> Source -> Generate toString()…

or with shortcuts

  • in editor press Alt + Shift + S -> press ‘S’

What you need to remember when overriding toString() manually?

  • Return as much information as needed (that may be interesting)
  • It is obligatory in data classes
  • if you decide that your toString() provide result in format presentable to the user, then you have to clearly document output print format and remain it unchanged for life. In that case you need to be aware that toString() output may be printed in UI somewhere
  • beside toString() you still need to provide accessor methods for class fields, if needed

Effective Java

Effective Java (Joshua Bloch) is a book with advanced Java programming techniques that make Java code more robust and readable. I am currently reading it and this is why these [Effective Java] posts come up here. These are summaries of chapters that are most valuable in my opinion.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: