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方法。
恍然大悟,芜湖,起飞
补充
将StringBuffer在屏幕上显示出来, 则必须首先调用toString方法把它变成字符串常量,因为PrintStream的方法println()不接受StringBuffer类型的参数.
public class Zhang
{
public static void main(String[] args)
{
String MyStr = new StringBuffer();
MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString();
System.out.println(MyStr);
}
}
toString()方法在此的作用是将StringBuffer类型转换为String类型.
public class Zhang
{
public static void main(String[] args)
{
String MyStr = new StringBuffer().append("hello").toString();
MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString();
System.out.println(MyStr);
}
}