看板 java 關於我們 聯絡資訊
各位前輩好,目前小弟研究this的用法,在讀"Java: How to Program, 3ed"的中譯本 ,裡面有個範例在講this的用法,如下: #Fig. 8.10: import javax.swing.*; import java.text.DecimalFormat; public class ThisTest { public static void main(String[] args) { SimpleTime t = new SimpleTime(12,30,19); JOptionPane.showMessageDialog(null, t.buildString(), "Demonstrating the \"this\" Reference", JOptionPane.INFORMATION_MESSAGE ); System.exit(0); } } class SimpleTime { private int hour, minute, second; public SimpleTime( int hour, int minute, int second){ this.hour = hour; this.minute = minute; this.second = second; } public String buildString(){ return "this.toString(): " + this.toString() + "\ntoString():" + toString() + "\nthis (with implicit toString() call):" + this; } public String toString(){ DecimalFormat twoDigits = new DecimalFormat("00"); return twoDigits.format(this.hour) + ":" + twoDigits.format(this.minute) + ":" + twoDigits.format(this.second) ; } } ============== 程式結束 =============== 結果印出來就是: this.toString(): 12:30:19 toString(): 12:30:19 this (with implicit toString() call): 12:30:19 我想請問的是紅色●的部份: 第一種 this.toString() 和 第二種 toString() 我了解 但第三種,"只寫了 this 就可以印出時間??(即呼叫toString這個method)" 我不能理解為什麼,this可以呼叫toString,我也有試著去寫toString1,看會如何 但this都只印toString 如果將toString給註解掉,this就會印出:SimpleTime@642b6fc7 (我自己理解這是 記憶體位置) 這我想了好久都想不透為什麼this可以指到toString...也有爬文跟google,但查到的 大部份this用法都是在說: this.member = local_member 這種用法 謝謝各位前輩orz -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.110.189
darkk6:http://ppt.cc/vSoN 參考物件的 toString,equals,hashcode 03/25 11:09
PsMonkey:是 + 號運算去呼叫 toString(),其餘同樓上 03/25 11:15
謝謝兩位前輩的回答,不過小弟我資質駑鈍Q__Q 還是不太懂... ※ 編輯: broodstare 來自: 140.115.110.189 (03/25 14:02)