[问题] this用法

楼主: broodstare (交给C4就对了)   2014-03-25 11:02:29
各位前辈好,目前小弟研究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
作者: darkk6 (Mr. Pan)   2014-03-25 11:09:00
http://ppt.cc/vSoN 参考物件的 toString,equals,hashcode
作者: PsMonkey (痞子军团团长)   2014-03-25 11:15:00
是 + 号运算去呼叫 toString(),其余同楼上

Links booklink

Contact Us: admin [ a t ] ucptt.com