Apple Py
Apple Py

Reputation: 51

Java Having classes take information from each other

Let's say you have two classes, one called Main and the other called Second. Second needs to take a variable from Main and Main needs to take a method from Second

Example:

public class Main 
{
  Second second = new Second();
  public int firstInt = 5;
  second.printThing();
}

public class Second 
{
    Main main = new Main();
    public void printThing() 
    {  
        System.out.println(main.firstInt);
    }
}

Since you can't do Main main = new Main(); and Second second = new Second; without getting a stack overflow exception, what are you supposed to do?

Upvotes: 1

Views: 55

Answers (2)

Eran
Eran

Reputation: 393781

Assuming the instances of Main and Second should hold references to each other, you can pass references to the constructors :

Main's constructor :

public Main (Second second)
{
    this.second = new Second (this);
}

Second's constructor :

public Second (Main main)
{
    this.main = main;
}

If, as the names imply, Second depends on Main (i.e. no isntance of Second can exist without an enclosing instance of Main), you can define Second to be an inner class of Main, in which case it would implicitly hold an instance of the enclosing class Main.

Upvotes: 4

A4L
A4L

Reputation: 17595

Don't use this kind of initialization, add a setter for each class in the other and set after construction.

Main m = new Main();
Second s = new Second();
m.setSecond(s);
s.setMain(m);

Upvotes: 0

Related Questions