我刚开始学习Java.我对构造函数的了解是:
它将在初始化对象时自动运行.
构造函数的名称与类名相同.
现在,下面是我开始感到困惑的地方.
class Frog{
public String toString() {
return "Hello";
}
}
public class App {
public static void main(String[] args) {
Frog frog1 = new Frog();
System.out.println(frog1);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题:既然public String toString ()不是构造函数,那么为什么在运行程序时它的行为就像构造函数一样.我以为它只能在我从App班级打电话时才能运行.
Coo*_*tri 12
简答:在调用堆栈中frog1.toString()使用公共方法调用. System.out.println(Object x)
但是怎么样?让我们一起找:)
看一下这个PrintStream类(System.out默认情况下哪个实例用作字段值)源代码及其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)
obj是frog1在你的情况下,其toString()方法被调用,并返回"Hello"String实例的控制台输出)