[Read Effective Java] Chapter 3 Item 10 "Always Override toString"

Always override toString

Even if I create a new class and try toString, I get a string like " PhoneNumber @ 163b91 " that I'm not happy to receive. The general contract for toString is "a concise but informative expression that is easy for people to read."

Sample code

/**
 *Returns a string representation of this phone number
 *The character string consists of 14 characters, and its format is"(XXX) YYY-ZZZZ"is.
 *XXX is the area code, YYY-ZZZZ is the city code.
 *(Each capital letter represents a one-digit number.)
 * 
 *Any of the three parts of this phone number can fill that field
 *If there are few digits, the field is padded with zeros.
 *For example, the last 4 digits of the number"123"If so, the last of the string representation
 *4 letters"0123"It will be.
 * 
 *Note that there is one space after the area code parentheses 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} "! Overriding toString exactly saves you the time of parsing another person's program using this class.

Continue

[Read Effective Java] Chapter 3 Item 12 "Considering Implementation of Comparable" https://qiita.com/Natsukii/items/1942f7f41ac39b914591

Recommended Posts

[Read Effective Java] Chapter 3 Item 10 "Always Override toString"
[Read Effective Java] Chapter 3 Item 9 "When overriding equals, always override hashCode"
[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers"
[Read Effective Java] Chapter 3 Item 12 "Considering Implementation of Comparable"
[Read Effective Java] Chapter 2 Item 6 "Remove obsolete object references"
Effective Java Chapter 2
Effective Java Chapter 6 34-35
Effective Java Chapter 4 15-22
Effective Java Chapter 3
[Read Effective Java] Chapter 2 Item 4 "Force uninstantiation with a private constructor"
[Read Effective Java] Chapter 2 Item 5 "Avoid the creation of unnecessary objects"
[Read Effective Java] Chapter 2 Item 1 "Consider static factory methods instead of constructors"
[Read Effective Java] Chapter 3 Item 8 "When overriding equals, follow the general contract"
[Read Effective Java] Chapter 2 Item 3 "Force singleton characteristics with private constructor or enum type"
Effective Java 3rd Edition Chapter 5 Generics
Effective Java 3rd Edition Chapter 8 Methods
[Read Effective Java] Chapter 2 Item 2 "Consider a builder when faced with a large number of constructor parameters"
java (override)
Effective Java 3rd Edition Chapter 9 Program General
Effective Java 3rd Edition Chapter 6 enums and annotations
Effective Java 3rd Edition Chapter 4 Classes and Interfaces
Effective Java 3rd Edition Chapter 7 Lambda and Streams
Effective Java 3rd Edition Chapter 2 Object Creation and Disappearance