1

so far I have seen one similar question: passing reference of class to another class, who just asked to pass a reference from class A to class B.

Well I did it so far only over the constructor.

This works as long as I do it only that simple way.

...

    this.classA = new ClassA(classB); //getting the null reference

    this.classB = new ClassB(classA); //getting the reference from new ClassA

...

classB will contain null because it is created after classA, says the null reference exists already.

Is there another way to access the reference after creation in class A?

Says the reference of new ClassB?

A code example would be amazing, since right now I don't understand the "solutions" which I have heard so far by creating multiple constructors... i am not even sure if they work.

edit: That is what my structure looks like

enter image description here

DestinationContentPanel--> DestinationMainPanel-->DestinationHealthMainPanel-->MainPanel<--BottomBarMainPanel<--LeftPanel

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

1

This sounds like a design you want to avoid. However if you must do it, i would recommend creating a class that holds references to both objects and pass that to classA and classB:

class RefHolder {
  ClassA a;
  ClassB b;
}

then use it:

RefHolder r = new RefHolder();
r.a = new ClassA(r);
r.b = new ClassB(r);
//at this point, both classes can use the RefHolder that was passed
//to the constructors to access instances of ClassA and ClassB

But this is only a workaround, I would advise to not use that type of circular dependency.

f1sh
  • 11,489
  • 3
  • 25
  • 51
  • First of all thank you very much! Second thing, that is the issue by doing so? – Baron von Hoot Mar 20 '19 at 10:45
  • 1
    It solves the issue of having a null reference inside ClassA because the instance of ClassB is set into the RefHolder which is available in ClassA. Of course you cannot work with the instance of classB inside of ClassA's constructor. – f1sh Mar 20 '19 at 10:50