How to initialize classes dependent on each other, in Java?

class, dependencies, java

Solution

For one of the classes, you don't provide the reference in the constructor, but you can use a `set`-method instead. Initializing them both dependent on each other when none of them previously exists seems difficult.

class Foo {
    private Bar bar;
    public Foo(Bar bar) {
        this.bar = bar;
    }
}

class Bar {
    private Foo foo;
    setFoo(Foo foo) {
        this.foo = foo;
    }
}


Bar bar = new Bar();
Foo foo = new Foo(bar);
bar.setFoo(foo);

Also note that there might be better solutions to this. Such as using an Observer-pattern, it all depends on how you plan on using your objects.

Problem

Say I have the class signatures ``` Class1(Class2 c); Class2(Class1 c); ``` How do I initialize both?

Original source