This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund 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
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply 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: 973

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: 16690
    
  19


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

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
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 agree. Here's the link: http://aspose.com/file-tools
 
subject: Override toString() when you want a mere mortal to be able to read something meanningful about the..
 
Similar Threads
Strings....
Comaparable And comparator
shift operators
when toString() is implicitly called
print a HashSet of objects