This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Override toString() when you want a mere mortal to be able to read something meanningful about the.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Override toString() when you want a mere mortal to be able to read something meanningful about the.." Watch "Override toString() when you want a mere mortal to be able to read something meanningful about the.." New topic
Author

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

Vishal Hegde
Ranch Hand

Joined: Aug 01, 2009
Posts: 1055

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?

http://www.lifesbizzare.blogspot.com || OCJP:81%
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18534
    
  40


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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19654
    
  18

David Newton wrote:

You mean don't you? Or do you usually include the HEX hash code in your toString implementations?


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

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.
 
jQuery in Action, 2nd edition
 
subject: Override toString() when you want a mere mortal to be able to read something meanningful about the..
 
Similar Threads
when toString() is implicitly called
shift operators
Strings....
print a HashSet of objects
Comaparable And comparator