创建本地和实例对象时出现 java StackOverflowError
大家好,有人可以解释一下为什么这段代码会给我 StackOverflowError 错误吗? 如果您能解释 instanceObj 初始化并调用 ObjectTest 构造函数和 java.lang.Object 构造函数时发生的情况,我真的很感激。在我看来,ObjectTest 构造函数一遍又一遍地循环。但我不知道确切的原因?所以任何建议...
public class ObjectTest {
public ObjectTest() {
}
ObjectTest instanceObj = new ObjectTest();
public static void main(String[] args) {
ObjectTest localObj = new ObjectTest();
}
}
Hi can anybody please explain me why is this code snippet giving me StackOverflowError
I 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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您调用构造函数来创建对象的新实例。它有对另一个实例的引用,您可以使用另一个新的 ObjectType 实例来初始化该实例,而该实例又会执行相同的操作。在出现该错误之前,需要进行无数次调用。
这会起作用。
You call the constructor to create a new instance of your object. It has a reference to another instance, which you initialize with another new instance of ObjectType which, in turn, does the same thing. it's an infinite number of calls until you get that error.
This will work.
让我们看看将执行什么:
main()
创建一个ObjectTest
的新实例,ObjectTest
类有一个字段instanceObj
其中将包含一个ObjectTest
,ObjectTest
初始化的instanceObj
我认为您想要更像这样的东西:
或者这个:
这就是单例模式。
关于同一主题:
Let's see what will be executed :
main()
create a new instance ofObjectTest
ObjectTest
class has a fieldinstanceObj
which will contain anObjectTest
instanceObj
in initialized with a newObjectTest
I think you wanted something more like this :
Or this :
This is the Singleton pattern.
On the same topic :
每个
ObjectTest
实例都引用另一个ObjectTest
— 名为instanceObj
。该实例是在创建其“父”实例时构建的……因此导致了另一个、另一个、无穷无尽的构建。下面是等效代码,可以更清楚地指出该缺陷:
Every
ObjectTest
instance refers to anotherObjectTest
—namedinstanceObj
. This instance is constructed when its "parent" instance is created… and thus results in construction of another, and another, ad infinitum.Here is equivalent code that may point out the flaw more clearly:
因为你正在递归地创造你自己。
您需要注入实例,或者让其他类管理该属性。
Because you are recursively creating yourself.
You need to inject your instance, or have some other class manage that property.