看板java
标 题Re: [问题] 请问toString的观念
发信站KKCITY (Mon Apr 24 16:54:57 2006)
转信站ptt!ctu-reader!Spring!news.nctu!news.ntu!bbs.ee.ntu!news.kkcity.com.tw
※ 引述《[email protected] (痞子军团团长)》之铭言:
> ※ 引述《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):449◤1999 电话(2):4058-6000
└──《From:61.30.73.247
》──┘▏帐号:kkcity 密码:kkcity
--