主要有toString方法,System.out.println("middle of zero: arg is " + arg);当然就调用toString方法,不止一个成员变量当然就得不到想要的值
誰說沒用pi.value和arg.value,static void zero(Pi arg) 里不就用了嗎 Pi类中有不止一个成员变量,當然是用Pi.* 重写toString方法讓你在 System.out.println("top of zero: arg is " + arg); arg.value = 0.0; System.out.println("middle of zero: arg is " + arg); arg = null; System.out.println("bottom of zero: arg is " + arg); 時輸出為 top of zero: arg is 3.1415 middle of zero: arg is 0.0 bottom of zero: arg is 而不必寫 System.out.println("top of zero: arg is " + arg.value); arg.value = 0.0; System.out.println("middle of zero: arg is " + arg.value); arg = null; System.out.println("bottom of zero: arg is " + arg.value);
2.重写toString的时候,比如
System.out.println(o);//o是你的对象
就会自动调用toString方法,也就是说
凡是需要toString的地方,就不会掉用Object.toString
而是你自己写的toString了
Pi类中有不止一个成员变量,當然是用Pi.*
重写toString方法讓你在
System.out.println("top of zero: arg is " + arg);
arg.value = 0.0;
System.out.println("middle of zero: arg is " + arg);
arg = null;
System.out.println("bottom of zero: arg is " + arg);
時輸出為
top of zero: arg is 3.1415
middle of zero: arg is 0.0
bottom of zero: arg is
而不必寫
System.out.println("top of zero: arg is " + arg.value);
arg.value = 0.0;
System.out.println("middle of zero: arg is " + arg.value);
arg = null;
System.out.println("bottom of zero: arg is " + arg.value);