Click here to Skip to main content
13,200,202 members (54,909 online)
Rate this:
Please Sign up or sign in to 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 20-Mar-12 9:25am
SAKryukov 20-Mar-12 15:38pm
I'm just curious: what else could you possibly expect?

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Of course it would happen if you do in this way. This is because you use endless mutual recursion, please see:[^].

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… :-)


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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.171020.1 | Last Updated 20 Mar 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100