This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
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....
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.