一葉笑天
          雄關漫道真如鐵, 而今邁步從頭越。 從頭越, 蒼山如海, 殘陽如血。
          posts - 73,comments - 7,trackbacks - 0
          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() {
          18return String.format("(%03d) %03d-%04d",
          19areaCode, 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 一葉笑天 閱讀(244) 評論(0)  編輯  收藏 所屬分類: JAVA技術
          主站蜘蛛池模板: 潢川县| 象州县| 呼玛县| 桂东县| 泸西县| 炎陵县| 前郭尔| 达拉特旗| 永兴县| 平塘县| 藁城市| 巴林左旗| 固镇县| 凤城市| 油尖旺区| 大厂| 皋兰县| 富源县| 漳州市| 惠东县| 确山县| 枝江市| 临城县| 平果县| 宁都县| 祁阳县| 绥江县| 彰武县| 赤壁市| 东乌珠穆沁旗| 黄陵县| 莲花县| 巴塘县| 偏关县| 于都县| 日照市| 怀安县| 五指山市| 日喀则市| 英超| 温宿县|