Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: classes with instance of each other [duplicate]

Tags:

java

I feel like this is a really basic question, but I've never got a situation like this. Right now I have a structure like this:

public class Main{
    ClassA a = new ClassA();
    ClassB b = new ClassB(a);
}

My ClassA is needed in ClassB as well as in the Main.class. Now I noticed that ClassA has to know ClassB as well.

public class Main{
    ClassA a = new ClassA(b);
    ClassB b = new ClassB(a);
}

Obviously won't work. First I thought of using a Observer Pattern but this seems to be an overkill to me, besides it's not what the pattern is usually used for.
Is there a way, that I can make Main.class know ClassA.class & ClassB.class, as well as make ClassA.class know ClassB.class and vice-versa? Since Main.class uses ClassA as well I have to have the same class only initialized once.

like image 353
Peter Avatar asked Feb 20 '26 10:02

Peter


1 Answers

You don't need to set the references in the constructor. You can create a setter which you can call after you've created both objects such as b.setA(a);.

like image 87
Kayaman Avatar answered Feb 23 '26 01:02

Kayaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!