为什么没有调用类中的toString()方法,却自动实现了转换?
package test;
public class MyDate {
int year;
int month;
int day;
void set(int y,int m,int d){
year=y;
month=m;
day=d;
}
void set(MyDate d){
set(d.year,d.month,d.day);
}
public String toString(){
return year+"年"+month+"月"+day+"日";
}
public boolean equals(MyDate d){
return this==d||d!=null&&year==d.year&&month==d.month&&day==d.day;
}
public static void main(String args[]){
MyDate d1=new MyDate();
d1.set(2009,7,16);
MyDate d2=d1;
System.out.println("d1:"+d1+",d2:"+d2+",d1==d2?"+(d1==d2));
d2.year=2008;
System.out.println("d1:"+d1+",d2:"+d2+",d1==d2?"+(d1==d2)+",d1.eguals(d2)?"+(d1.equals(d2)));
d2=new MyDate();
d2.set(d1);
System.out.println("d1:"+d1+",d2:"+d2+",d1==d2?"+(d1==d2)+",d1.eguals(d2)?"+(d1.equals(d2)));
}
}输出结果是:
d1:2009年7月16日,d2:2009年7月16日,d1==d2?true
d1:2008年7月16日,d2:2008年7月16日,d1==d2?true,d1.eguals(d2)?true
d1:2008年7月16日,d2:2008年7月16日,d1==d2?false,d1.eguals(d2)?true
代码中并没有调用过toString()方法,为什么最后输出的时候会自动调用了呢?