java.lang.Object提供toString方法。一般它包含類型+@+無符號的十六進制的hashcode值。例如“PhoneNumber@163b91.”
提供一個toString方法將會使類更便于使用。toString方法將會在println,printf,assert調用的時候自動調用。如果提供一個好的toString方法給PhoneNumber,可以很容易的提供診斷消息:
System.out.println("Failed to connect: " + phoneNumber);
在實踐中,toString方法應該返回對象包含的所有感興趣信息。
在實現toString方法的時候需要決定是否需要指定返回值的格式。在值對象類中,是需要指定的。
指定格式的好處是它將對象變成一個標準的,清楚的,可讀的對象。缺點是toString將會返回你指定的格式。而你將不能修改它。
是否需要指定格式,需要清楚的文檔化你的意圖。例如:
1
/** *//**
2
* Returns the string representation of this phone number.
3
* The string consists of fourteen characters whose format
4
* is "(XXX) YYY-ZZZZ", where XXX is the area code, YYY is
5
* the prefix, and ZZZZ is the line number. (Each of the
6
* capital letters represents a single decimal digit.)
7
*
8
* If any of the three parts of this phone number is too small
9
* to fill up its field, the field is padded with leading zeros.
10
* For example, if the value of the line number is 123, the last
11
* four characters of the string representation will be "0123".
12
*
13
* Note that there is a single space separating the closing
14
* parenthesis after the area code from the first digit of the
15
* prefix.
16
*/
17
@Override public String toString()
{
18
return String.format("(%03d) %03d-%04d",
19
areaCode, prefix, lineNumber);
20
}
如果你不打算指定格式,文檔結構應該像這樣:
1
/** *//**
2
* Returns a brief description of this potion. The exact details
3
* of the representation are unspecified and subject to change,
4
* but the following may be regarded as typical:
5
*
6
* "[Potion #9: type=love, smell=turpentine, look=india ink]"
7
*/
8
@Override public String toString()
{
}
在閱讀了上面的文檔后,編寫代碼的或者依賴詳細格式維護數據的程序員將會在格式變化時開始抱怨。
不管你是否指定格式,需要toString來返回包含信息的值。
posted on 2008-07-01 21:31
一葉笑天 閱讀(241)
評論(0) 編輯 收藏 所屬分類:
JAVA技術