在main方法之外创建对象时出现stackoverflow错误 [英] stackoverflow error when creating object outside the main method
问题描述
运行此代码时,它显示Stackoverflow错误。是什么我做错了,为什么代码编译?
While running this code it shows Stackoverflow error. What is it I am doing wrong, why does the code compile?
public class Foo {
int a = 5;
Foo f = new Foo();
void go() {
System.out.println(f.a);
}
public static void main(String[] args) {
Foo f2 = new Foo();
f2.go();
}
}
推荐答案
你只能使用实例调用 go
方法。所以在打电话之前,c'tor已经开始上课 Foo
You can call go
method with an instance only. so before call to go started, c'tor has run for class Foo
现在,C'tor被设计了初始化所有实例成员。
Now, C'tor is designed to initialize all instance members.
因此逐个初始化:
a初始化为5
a is initialized to 5
f被初始化为一个对象//但这里是catch,f永远不会被启动。
f is initialized to an Object // but here is the catch, f never gets initilized.
在 =
运算符工作之前,C'tor被调用,因此链继续。
before =
operator works, C'tor is called and thus the chain continues.
如果你看到堆栈跟踪,它将写入 init
。所以它只在初始化期间失败。
If you see the stacktrace, it'll have init
written in it. so it's failing during initialization only.
这篇关于在main方法之外创建对象时出现stackoverflow错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!