student的类重写toString方法的时候:
public class Student {
private String name;
private int age;
@Override
public String toString(){
return "名字:" + name + "," + "年龄:" + age;
}
}
class A {
public static void main(String[] args){
Student student = new Student("那鲁多",16);
System.out.println(student);
}
}
println输出就是调用了student的toString
student的类没有重写toString方法的时候
public class Student {
private String name;
private int age;
// @Override
// public String toString(){
// return "名字:" + name + "," + "年龄:" + age;
// }
}
class A {
public static void main(String[] args){
Student student = new Student("那鲁多",16);
System.out.println(student);
}
}
Object 的toString
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
pirntln输出的就是调用Object的toString
return getClass().getName()就是类名。类名=包+类名。
Integer.toHexString(hashCode())就是地址
那么为什么会println会调用toString呢?
看一下println的参数:
看一下参数是对象时候的println的源码
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
再看一下String.valueOf(x)的源码
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
可以发现是确实println参数是对象的时候是调用了对象的toString方法。