Re: [問題] 請問toString的觀念

看板java作者時間19年前 (2006/04/24 17:32), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串6/25 (看更多)
※ 引述《PsMonkey.bbs@ptt.cc (痞子軍團團長)》之銘言: > ※ 引述《seekyou (galagala~￾N )》之銘言: > : 如題,toString 會傳回物件的字串表示法,意即將物件轉成字串 > : 下面有個小程式 > : public class Employee { > : String name; > : int age; > : public static void main(String args[]) { > : Employee tom =new Employee(); > : System.out.println(tom); > : System.out.println(tom.toString()); > : } > : } > : 下面兩行印出的結果都是一樣的,不過為什麼toString()可加可不加呢? > : 可能對大家來說是理所當然的事 不過還是希望能聽聽各位的解說,非常謝謝 > 請看 System.out 的說明 > 然後找到 java.io.PrintStream > 然後看一下 println(Object) 跟 println(String) 這兩個 method。 > 也或許,你可以自己包一個 output 的 class > 然後來交叉測試一下 > public class PsOut{ > public static void println(Object obj){ > System.out.println("Sorry, PsMonkey can't handle this"); > } > public static void println(String str){ > System.out.println(str); > } > } 以他的程式來說, class Employee 沒定義 toString() method, 把 object 當引數傳入後,會呼叫到 Object.toString() 無論有沒有指明 toString() 結果為什麼會不同? 覺得很好奇! -- ┌─────KKCITY─────┐ KK免/費/撥/接 bbs.kkcity.com.tw 電話(1):4491999 電話(2):4058-6000 └──From:61.30.73.247 ──┘帳號:kkcity 密碼:kkcity --
文章代碼(AID): #14J9iL00 (java)
文章代碼(AID): #14J9iL00 (java)