This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma 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


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: 1067

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: 20029
    
  44


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: 20077
    
  30

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 - OCEJPAD 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.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Override toString() when you want a mere mortal to be able to read something meanningful about the..
 
It's not a secret anymore!