如果不调用toString方法,直接打印对象时,打印的是对象的地址值 [Java] 纯文本查看 复制代码 package ToStringTest;
public class Test {
public static void main(String[] args) {
Student student=new Student("Jack");
System.out.println(student);
}
}
class Student {
private String name;
public Student(String name) {
this.name = name;
}
}
[Java] 纯文本查看 复制代码 /**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
[Java] 纯文本查看 复制代码 /**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
通过以上代码,我们可以看到不调用toString方法打印student对象时,在底层依然调用了“toString()”方法。所以此处更恰当地描述应为“不重写‘toString()’方法时,打印的是地址值”。另外重写之后打印时,也就无需再写“toString()”了,因为在底层会调。
|