爲什麼輸出? :球體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