• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString Clarification

 
Mitch Krah
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone provide clarification of the toString method and overriding it in classes to print "meaningful" information? I have been asked to implement the toString method in classes but can only find a paragraph on this method in 2 different books. Any additional/practicle information would be appreciated.

Thank you,
M
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34965
377
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mitch,
By default the toString() method outputs a hash representing the memory address. Often, we overwrite this to contain useful information about the state of the object (such as the values of it's fields.) As an example,
 
Mitch Krah
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.

And then, how do you call the toString from another class?

M
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
either
System.out.println( myObject );
or
System.out.println( myObject.toString() );

It makes no never mind.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Appending an object reference to a String using the + operator will call toStrnig() on the reference (or append "null" if it's null) for you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic