2. java.lang.Object#toString()
• … 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. …
java.lang.Object#toString()
public String toString() {
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
3. toString() 오버라이딩의 장점
• println(), printf(), +, assert(), 디버거 출력 등의 여러 경우
에 객체가 전달되면 toString() 호출
Person p1 = new Person("01087891074", "sungho", 23, 0);
System.out.println(p1);
Logger log = Logger.getLogger(Person.class);
log.info(p1);
ERROR : The method info(String) in the type Logger is not
applicable for the arguments (Person)
4. toString() 오버라이딩의 장점
• toString() 을 잘 구현하면, 자신의 인스턴스는 물론 그 인
스턴스들의 참조를 갖고 있는 객체들도 toString()의 장점
을 가질 수 있다.
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("key", new Person("01087891074", "sungho", 23, Gender.MAN));
System.out.println(map);
{key=Person
[phonNum=01087891074, name=sungho, age=23, gender=MAN, getClass()=cl
ass
com.item10.Person, hashCode()=1711790973, toString()=com.item10.Person
@6607db7d]}
6. toString() 구현하기
• 가능하면 객체의 모든 중요한 정보를 반환해야 한다.
• 객체가 너무 크거나, 문자열로 바로 변환하기 어려운 상태
값을 갖는 경우는 요약된 정보만을 반환
– 예) Thread 메소드
• 값 클래스라면 API문서에 상세하게 규정
– API 문서의 표현으로 XML문서처럼 입출력에 사용 가
능
• 표현 형식의 규정 여부와는 무관하게 그 의도를 명쾌하게
문서화해야 한다.
7. cf) Thread.toString()
• System.out.println(thread);
Thread [main, 5, main]
/**
* Returns a string representation of this thread, including the
* thread's name, priority, and thread group.
*
* @return a string representation of this thread.
*/
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
return "Thread[" + getName() + "," + getPriority() + "," +
group.getName() + "]";
} else {
return "Thread[" + getName() + "," + getPriority() + "," +
"" + "]";
}
}