为什么输出? :球体0为什么这个Java代码隐式调用toString()方法?
不知何故,它隐式地调用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
有没有神奇的,它不是,做它的“Java”,但'println'方法。你可以自己实现这样的方法。 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/io/PrintStream.java#820 –
在println()中传递对象总是给出toString表示 – Kahn
这不是“隐含的”,它是“明确的”,只是看看'println'的作用。 – Tom