Reputation:
As a form of habit, I typically avoid keeping things in static methods for testing and for ease-of-use down the line in my java projects. However, in the past I have had to use a messy mix of static and non-static methods revolving around my main class, because I only know of one way to create a non-static instance of the class. Typically, I do this as a global variable, rather than load the class methods in each method.
For an example, let's say I have class MainGUI and ProjMain. In ProjMain, I use the global variable:
private MainGUI gui = new MainGUI();
This works very well, however if I have methods within the ProjMain class I want to access from the MainGUI class, naturally I go to do the same.
private ProjMain project = new ProjMain();
In this, I create a StackOverflowError. Is there a simple way to get the instance of the class as a variable, without having to put the variable in individual methods as opposed to global methods?
Upvotes: 0
Views: 169
Reputation: 20450
Hovercraft's solution is pretty good, here i have another one for you:
If you have lots of classes reference to each other, you should consider to extract a higher layer for them, the higher layer class should looks like this:
class HigherLayer {
public void dosomething(ProjMain pm, MainGUI mg){
pm.hello(mg);
mg.bye(pm);
}
}
And remove the global variables from ProjMain and MainGUI to make them less coupling.
Upvotes: 2
Reputation: 285401
Your classes have references to each other, and this is OK, but not if each creates a new reference to the other since this will do nothing but cause an infinite recursion with one creating an instance of the other, which creates an instance of the first, which creates an instance of the other, which creates an instance of the first, which creates an instance of the other, ..... etc...
To solve this, have one object create the other, but simply pass a reference to itself into the other via it's constructor or a setter method.
For example, the first class:
public class FirstClass {
private SecondClass secondClass;
public FirstClass() {
secondClass = new SecondClass(this);
}
and the other class
public class SecondClass {
private FirstClass firstClass;
public FirstClass(FirstClass firstClass) {
this.firstClass = firstClass;
}
Upvotes: 1