System.out.println

当时还没弄懂,它怎么就调用了toString方法呢?后来才知道println方法会自动调用toString方法,而这里的toString方法又发生了变化,所以才会输出以上格式化信息。

具体过程:println首先调用的是对象的valueOf方法,而valueOf方法则是调用了对象的toString()方法,toString()方法原来是返回对象的格式化信息的,所以如果不重写toString(),那么就会打印这串字符的哈希值,重写的话就能把重写后的格式打印出来。
参考链接
println()源码:

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

  String.valueOf()源码:

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

  toString()源码:

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

  

写出优雅代码
原文地址:https://www.cnblogs.com/birdterror/p/12698310.html