what is the use of toString() in java [duplicate]
Possible Duplicates:
What are the original reasons for ToString() in Java and .NET? when to use toString() method
what is main use of toString() in java
As the javadoc says:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
You can use this for:
- logging
- debugging
- representing in UI
etc.
However, it is advisable that you use it only for internal purposes, like logging and debugging.
The main use of toString()
is allowing arbitrary objects to be printed or logged.
In short, you come up with a String representation of your class, so you'll see meaningful values in your logs or when debugging instead of the default YourClass@38c313
. This representation is completely arbitrary.
For details, have a look at Item 10 in Effective Java, it has a couple of pretty good advices.
Just to add, sometimes it is useful to convert some object to a textual representation, and then define a constructor which can create an object out of this textual representation, something like
public Foo(String textualRep) {
}
I've seen this approach somewhere in used in the JDK but can't remember where.
精彩评论