Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Override toString() when you want a mere mortal to be able to read something meanningful about the..

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Override toString() when you want a mere mortal to be able to read something meanningful about the objects of your class.


Courtesy : SCJP 6.0 (Luv you kathy for the awesome book)



Can someone please provide a simple example regarding this?
 
Henry Wong
author
Marshal
Pie
Posts: 21115
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

When someone prints your object, the println() method calls the toString() method to get the string to print. So... do you want to override the toString() method so that you get something sensible printed to the screen? Or do you want your object to inherit the toString() method from the Object class (assuming that's your super class), and just get the name of your class and the hashcode?

Henry
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Newton wrote:

You mean don't you? Or do you usually include the HEX hash code in your toString implementations?
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I *always* include it; without it I often have to fire up a debugger (which I almost never use) just to find out if an issue is coming from same/different object references. I can't think of a good reason not to include it by default. Although in real life I also almost always use some form of ToStringBuilder.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic