1

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

5
  • Your question doesn't make much sense: stack overflow errors are caused by calling too many nested methods, not by creating objects. Commented Nov 2, 2012 at 22:46
  • 2
    @Wyzard: It makes perfect sense - initializing a Secondary requires initializing a new Main, which requires initializing a new Secondary etc. It's recursive construction, rather than recursive method calls. Commented Nov 2, 2012 at 22:51
  • @JonSkeet, only if the calls are in the constructor, which the question doesn't specify, though it seems like a plausible interpretation. I'd assumed that the first sentence was referring to code in a static main() method. Commented Nov 2, 2012 at 22:59
  • @Wyzard: Those are clearly field declarations (otherwise private would be invalid), with variable initializers. Commented Nov 2, 2012 at 23:10
  • Good point. I wasn't reading carefully enough. Commented Nov 2, 2012 at 23:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.