Caffeinated Coder
Caffeinated Coder

Reputation: 680

Given two classes, creating an object of each class in one another results in StackOverflow Exception

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.

Upvotes: 0

Views: 1511

Answers (2)

Michael Krussel
Michael Krussel

Reputation: 2656

You should be passing an instance of one of you classes into the constructor of the other class.

public class Main {
   private final GUI gui;
   Main() {
      gui = new GUI(this);
   }
}

public class GUI {
   private final Main main;
   public GUI(Main main) {
      this.main = main;
   }
}

You could also use setters instead of constructors. I don't like this option as much, because you lose the ability to make your variables final.

public class Main {
   private GUI gui;
   Main() {
   }
   public void setGui(GUI gui) {
      this.gui = gui;
   }
}

public class GUI {
   private Main main;
   public GUI() {
   }
   public void setMain(Main main) {
      this.main = main;
   }
}

public static void main(String[] args) {
   Main main = new Main();
   GUI gui = new GUI();
   main.setGui(gui);
   gui.setMain(main);
}

Upvotes: 6

Jigar Joshi
Jigar Joshi

Reputation: 240948

Singleton ? (if it works for your app )

Upvotes: 0

Related Questions