前言
我最近在系统整理一些 Java 后台方面的面试题和参考答案,有找工作需求的童鞋,欢迎关注我的 Github 仓库,如果觉得不错可以点个 star 关注 :
最近在看《Java编程思想》,看到第七章复用类那里的时候,发现 new 了对象之后调用 System.out.println() 打印对象的时候,如果对象不为 null
根本不用显式地调用类的 toString() 方法,还是会默认调用类的 toString() 方法。于是带着好奇心看了下 PrintStream 的 println() 方法的源码,果然发现,源码之中一切尽显。书中具体代码如下:
/**
* @author Rotor
* @date 2019/6/2 21:19
*/
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = "Constructed";
}
public String toString() {
return s;
}
}
public class Bath {
private String // Initialization at point of definition;
s1 = "Happy",
s2 = "Happy",
s3, s4;
Soap s5;
private Soap castitle;
private int i;
private float toy;
public Bath() {
System.out.println("Inside Bath()");
s3 = "Joy";
toy = 3.14f;
castitle = new Soap();
}
// Instance initialization:
{i = 47;}
public String toString() {
if (s4 == null) { // Delayed initialization:
s4 = "Joy";
}
if (s5 == null) { // Delayed initialization:
s5 = new Soap();
}
return
"s1 = " + s1 + "\n" +
"s2 = " + s2 + "\n" +
"s3 = " + s3 + "\n" +
"s4 = " + s4 + "\n" +
"i = " + i + "\n" +
"toy = " + toy + "\n" +
"castitle = " + castitle + "\n" +
"s5 = " + s5;
}
public static void main(String[] args) {
Bath b = new Bath();
System.out.println(b);
}
}
上面的代码中,执行 System.out.println(b);
语句时,会自动调用 Bath 类的 toString() 方法,具体可以看下 println() 方法的源码,如下:
重点在 String s = String.valueOf(x);
这一行代码的执行,点开可以看到如下:
可以很清楚地看到,调用 System.out.println(b);
打印对象 b
时,因为对象 b
不为 null,所以会自动调用 Bath
类的 toString()
方法。