| Author |
toString Clarification
|
Mitch Krah
Ranch Hand
Joined: Sep 06, 2004
Posts: 41
|
|
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
internet detective
Marshal
Joined: May 26, 2003
Posts: 26193
|
|
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,
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Mitch Krah
Ranch Hand
Joined: Sep 06, 2004
Posts: 41
|
|
Thank you. And then, how do you call the toString from another class? M
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
either System.out.println( myObject ); or System.out.println( myObject.toString() ); It makes no never mind.
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
David Harkness
Ranch Hand
Joined: Aug 07, 2003
Posts: 1646
|
|
|
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.
|
 |
 |
|
|
subject: toString Clarification
|
|
|