开发者

what is the use of toString() in java [duplicate]

This question already has answers here: 开发者_如何学Python Closed 12 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜