给定两个类,在每个类之间创建一个对象会导致StackOverflow Exception. [英] Given two classes, creating an object of each class in one another results in StackOverflow Exception.

查看:147
本文介绍了给定两个类,在每个类之间创建一个对象会导致StackOverflow Exception.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个类,在每个类之间创建一个对象会导致StackOverflow异常.这是一个JAVA项目.

我的项目中有多个类,要使用其他类,我想我会创建另一个类的对象并使用它.

说我有Main类和GUI类.我已经在MAIN中创建了GUI对象并对其进行了初始化.同样,我已经在GUI中创建了MAIN对象并对其进行了初始化.

现在,这给了我一个Stack Overflow异常,因为构造函数的调用将深入到递归中.

我该怎么办?

我想到的一种可能的解决方案是使一类变量和方法成为STATIC.

还有其他解决方案吗?请提出建议.

Given two classes, creating an object of each class in one another results in StackOverflow Exception. It is a JAVA project btw.

There are multiple classes in my projects and for using the other classes, I thought i would create objects of the other class and use it.

Say i have class Main and class GUI. I have created object of GUI in MAIN and initialized it. Similarly i have created an object of MAIN in GUI and initialized it.

Now this gives me a Stack Overflow Exception as the the constructor calls are going deep into recursion.

How do i go about it?

One possible solution i can think of is making variables and methods of one class STATIC.

Any other solution? Please suggest.

推荐答案

当然,如果您这样做,就会发生这种情况.这是因为您使用了无休止的相互递归,请参见:
http://en.wikipedia.org/wiki/Mutual_recursion [
Of course it would happen if you do in this way. This is because you use endless mutual recursion, please see:
http://en.wikipedia.org/wiki/Mutual_recursion[^].

You should change your design the avoid constructing of the objects of mutually dependent classes in constructors. Isn''t that obvious that such type of mutual recursion cannot ever end?

To start with, the stack overflow problems are probably the easiest to debug. You put a breakpoint at the very beginning of the method which might be called recursively, and, when executions stops there, look at the call stack to see where a call comes from.

The resolution of the problem really depends on you goal. First of all, think why do you need two objects of different types to reference each other. If you really need it, which always happens, think about the constraint: when some of these two references can be null and what it should mean. Anyway, you already should see that you cannot construct both in the constructor, as this dependency is circular. You should leave one or both of the cross-references to be null at the moment of the completed construction. The reference which is not constructed can be presented as a read-write property, so you could assign the reference to the instance of the object constructed separately.

This is really much easier to understand and implement than to explain… :-)

—SA


这篇关于给定两个类,在每个类之间创建一个对象会导致StackOverflow Exception.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆