楼主想问的是为什么System.out.println(x)自动调用toString()吧
在java.io.PrintStream.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();
- }
- }
复制代码 所有的类又都继承Object类
这样就很明显了 |