• 01-31-2011, 05:31 PM
felito
hi guys

i have a recursive problem. I have two classes and i need to instantiate them mutually.

so the result is the Stackoverflow error

how i can solve that?

my first class - King() (have more code, but is irrelevant for the case)

Code:

```        final Rules result = new Rules();                 final Cards gr = new Cards();                 play2a = gr.GameRules2();                 play2aa = gr.GameRules3(); ActionListener five = new ActionListener() {                         public void actionPerformed(ActionEvent e) {                         pn10.setText(result.test());                         }                 };```
second class - Rules
Code:

```public class Rules {         final King rules = new King();         public String test() {                 if (rules.play2a > rules.play2aa) {                         String result = "Player 1 get all cards";                         return result;                 } else {                         String result_ = "Player two get all cards";                         return result_;                 }         } }```

thanks :)
• 01-31-2011, 05:51 PM
Tolls
You need to decide whether a King has Rules, or whether Rules have a King.

If the King in Rules is simply supposed to be a reference to the one creating the Rules then don't create it there, simply pass in "this" to a Rules constructor:
Code:

`final Rules result = new Rules(this);`
Of course this is based on almost no idea what your requirements are, since you haven't told us.
• 01-31-2011, 09:03 PM
felito
I tried but it didn't work

i don't know how i can solve that...
• 01-31-2011, 11:01 PM
What tolls is saying, is this.

If all A's have a B and all B's have an A, how do you make the first A before you've made a B? Or, how do you make the first B without an A?

This is a circular dependency. As Tolls said, something has to come first, otherwise you have a chicken and egg situation, and java creates stack entries until it overflows. Decide which class contains the other by definition - you can't have it both ways.
• 02-01-2011, 09:52 AM
Tolls
Well, they can have both , they just can't create both. My description was a bit off, it should have said "creates" rather than "has".

But the rest stands. You need to decide who does the creating.

Since a King seems to have Rules and the Rules are specific to the King (again, based on the amount of information you have supplied), then the King creates the Rules and the Rules accept a King reference.

If you say you've tried but it didn't work then show us, because we can't explain where you've gone wrong without actually seeing it.