为什么print语句在java中调用**toString**方法?

为什么print语句在java中调用**toString**方法?

问题描述:

为什么下面的代码段会自动调用toString()方法?

Why the following code segment auto calls toString() method?

public class Demo {
   public Demo() {
    System.out.println(this); // Why does this line automatically calls toString()?
    }

   public static void main(String[] args) {
    Demo dm = new Demo();
   }
}

println 针对各种类型重载,您调用的是:

println is overloaded for various types, the one you are invoking is:

java.io.PrintStream.println(java.lang.Object)

看起来像这样:

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().QED

So you can see it calls toString() on your object. QED