本文介绍了本地和实例对象创建时的java StackOverflowError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能解释一下为什么这段代码片段给了我 StackOverflowError如果您能解释在 instanceObj 初始化和调用 ObjectTest 构造函数和 java.lang.Object 构造函数时发生了什么,我真的很感激.在我看来 ObjectTest 构造函数循环一遍又一遍.但我不知道确切的原因?所以任何建议...
Hi can anybody please explain me why is this code snippet giving me StackOverflowErrorI really appreciate if you can explain what is happening when instanceObj initializing and calling ObjectTest constructor and java.lang.Object constructor. It seems to me ObjectTest constructor loop over and over.But I don't know exact reason? So any suggestion...
public class ObjectTest {
public ObjectTest() {
}
ObjectTest instanceObj = new ObjectTest();
public static void main(String[] args) {
ObjectTest localObj = new ObjectTest();
}
}
推荐答案
让我们看看会执行什么:
Let's see what will be executed :
main()
创建一个ObjectTest
的新实例ObjectTest
类有一个字段instanceObj
,它将包含一个ObjectTest
- 使用新的
ObjectTest
初始化的 - 转到第 2 步
instanceObj
main()
create a new instance ofObjectTest
- the
ObjectTest
class has a fieldinstanceObj
which will contain anObjectTest
- the
instanceObj
in initialized with a newObjectTest
- go to step 2
我想你想要更像这样的东西:
I think you wanted something more like this :
public class ObjectTest {
private static ObjectTest instanceObj;
private ObjectTest() {
}
public static ObjectTest getInstance() {
if (instanceObj != null) {
instanceObj = new ObjectTest();
}
return instanceObj;
}
public static void main(String[] args) {
ObjectTest localObj = ObjectTest.getInstance();
}
}
或者这个:
public class ObjectTest {
private static final ObjectTest instanceObj = new ObjectTest();
private ObjectTest() {
}
public static ObjectTest getInstance() {
return instanceObj;
}
public static void main(String[] args) {
ObjectTest localObj = ObjectTest.getInstance();
}
}
这是单例模式.
关于同一主题:
这篇关于本地和实例对象创建时的java StackOverflowError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!