Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
Posted
Comments
Sergey Alexandrovich Kryukov 20-Mar-12 15:38pm    
I'm just curious: what else could you possibly expect?
--SA

1 solution

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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900