1、源代码长什么样?
public String toString(){
return this.getClass().getName() + "@" + Integer.toHexString(hashCode());
}
源代码上 toString() 方法的默认实现是:
类名 @ 对象的内存地址转换为十六进制的形式
2、SUN公司设计 toString() 方法的目的是什么?
toString() 方法的设计目的是:通过调用这个方法可以将一个“Java对象”转换成“字符串表示形式”
3、SUN 公司开发Java语言的时候,建议所有的子类都去重写 toString() 方法。
toString() 方法应该是一个简洁的、详实的、易阅读的。
以下代码加深理解
public class Test3{
public static void main(String[] args) {
MyTime t1 = new MyTime(2001,10,24);
String s1 = t1.toString();
// System.out.println(s1);
// 重写toString方法之前输出结果为:exercise.homework.java_test.src.exercise.homework.MyTime@1540e19d
System.out.println(s1);
// 重写toString方法之后输出结果为:2001年10月24日
}
}
class MyTime{
private int year;
private int month;
private int day;
public MyTime(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public MyTime() {
}
public String toString(){
return this.year + "年" + this.month + "月" + this.day + "日";
}
}
输出结果为:



