Create objects without causing a stack overflow error?

只谈情不闲聊 提交于 2019-11-27 08:28:41

问题


So, I have my main class that calls private Secondary secondary = new Secondary(); when it runs. In the Secondary class, at the top I have code that says private Main main = new Main();.

How will I be able to use all of the methods and variables from the Secondary class and vice versa without causing a stack overflow error?

Note: they are not in the constructor


回答1:


Your Main class is creating a Secondary instance, which is creating a Main instance..., and this is causing the stack overflow error.

I think you just want the objects to refer to each other, so don't create the other class's new instance in the constructor. Declare references as instance variables, and use setter methods to store existing references to objects of the other type.




回答2:


You could use the builder pattern to handle safe (non-recursive) initialization of your instance fields (via setters).



来源:https://stackoverflow.com/questions/13203992/create-objects-without-causing-a-stack-overflow-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!