[Java] [Read Effective Java] Chapter 3, Item 10 Always override toString

1 minute read

Always override #toString

Even if you create a new class and try toString, you will get a string that you are not happy with, such as "[email protected]". The general contract for toString is “brief, yet informative, human-readable.”

Sample code

 * Returns a string representation of this phone number
 * The character string consists of 14 characters and its format is "(XXX) YYY-ZZZZ".
 * XXX is the area code and YYY-ZZZZ is the local area code.
 * (Each capital letter represents a single digit.)
 * Any of the three parts of this phone number to fill in that field
 If there are fewer * digits, the field is padded with 0s at the beginning.
 * For example, if the last four-digit number is "123", the last character in the string
 * 4 characters are "0123".
 * Please note that there is one space after the area code to separate it from the area code.
@Override public String toString(){
    return String.format("(%03d) %03d-%04d",
                         areaCode, prefix, lineNumber);

This will return "{Jenny=(707) 867-5309}"! Exactly overriding toString saves you the time of parsing another person’s program that uses this class.


[Read Effective Java] Chapter 3, Item 12 “Examine the implementation of Comparable” https://qiita.com/Natsukii/items/1942f7f41ac39b914591