Item 10: Always override toString

1.    The string returned by Object.toString consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code.


2.    Providing a good toString implementation makes your class much more pleasant to use. (The client of your class will generate diagnostic messages in well-formed fashion.)

 

3.    It is impractical if the object is large or if it contains state that is not conducive to string representation. Under these circumstances, toString should return a summary such as ”Thread[main,5,main]”.

 

4.    The advantage of specifying the format of toString result is that it serves as a standard, unambiguous, human-readable representation of the object. It is recommended that you do this for value classes. If you specify the format, it’s usually a good idea to provide a matching static factory or constructor so programmers can easily translate back and forth between the object and its string representation. This approach is taken by many value classes in Java including BigInteger, BigDecimal and most of the boxed primitive classes.


5.    The disadvantage of specifying the format of the toString return value is that once you’ve specified it, you’re stuck with it for life, assuming your class is widely used. Programmers will write code to parse the representation, to generate it, and to embed it into persistent data.


6.    Whether or not you specify the format, provide programmatic access to all of the information contained in the value returned by toString.


7.    Whether or not you decide to specify the format, you should clearly document your intentions. (Give some example of the string you might return)

你可能感兴趣的:(toString,Effective Java)