tim*_*thy -1 java printing tostring implicit
为什么是输出?:球体 0
它以某种方式隐式调用 toString() 方法?这是如何运作的 ?
class BerylliumSphere {
private static long counter = 0;
private final long id = counter++;
public String toString() {
return "Sphere " + id;
}
}
public class Test {
public static void main (String[] args) {
BerylliumSphere spheres = new BerylliumSphere();
System.out.println(spheres);
}
}
// output: Sphere 0
Run Code Online (Sandbox Code Playgroud)
System.out是PrintStream的静态成员的实例System。该类有一个接受类型参数的PrintStream函数。该函数在 Open JDK 中如下所示:println()Object
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你看一下String.valueOf(),它接受类型 的参数Object,你可以看到:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Run Code Online (Sandbox Code Playgroud)
没有魔法。它只是一个调用toString对象的 Java 类。
进一步阅读