It's not a secret anymore!*
The moose likes Java in General and the fly likes overriding toString properly Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "overriding toString properly" Watch "overriding toString properly" New topic
Author

overriding toString properly

Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

Hi All,
I want to make sure that I am overriding toString method for an object in the correct way. My understanding is that the method should include information about all public fields, but what about private fields? My hunch is that it should not. What do others think?

thanks,
Barry
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
I don't even think you have to supply all public "fields" in toString. Maybe if your object is just nothing more than a data container. But if an object is an ... err, well ... Object, then toString should give you a "readable" text representation of that object. That might or might not include its full state, but should be enough to identify what it is and what it is doing.
For example, look at java.net.Socket (I just picked one out of the blue). It has public "fields" (get/set methods) for things like soLinger, receiveBufferSize, keepAlive, etc. But the only thing that toString reports is address, port, and localport. This is enough to tell you "this is a socket connection to www.foo.com port 80 using localport 6543", which is probably all you really need to identify the object.
Also note there is potentially a maintainence issue - if you add features to your object (like Socket added keepAlive in 1.3), do you always have to update toString every time? And does changing toString's output (if it was documented) represent a change in the "contract"? Things to consider....
Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

Also note there is potentially a maintainence issue - if you add features to your object (like Socket added keepAlive in 1.3), do you always have to update toString every time?

Good point! So basically, it is up to the developer to provide enough information about the object so that anyone calling this method would have the necessary information to be able to tell what the object is.

thanks,
Barry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: overriding toString properly