I have the following classes.
public class B
{
public A a;
public B()
{
a= new A();
System.out.println(\"Creating B\");
}
A similar workaround to getters/setters using composition and and constructor injection for the dependencies. The big thing to note is that the objects don't create the instance to the other classes, they are passed in (aka injection).
public interface A {}
public interface B {}
public class AProxy implements A {
private A delegate;
public void setDelegate(A a) {
delegate = a;
}
// Any implementation methods delegate to 'delegate'
// public void doStuff() { delegate.doStuff() }
}
public class AImpl implements A {
private final B b;
AImpl(B b) {
this.b = b;
}
}
public class BImpl implements B {
private final A a;
BImpl(A a) {
this.a = a;
}
}
public static void main(String[] args) {
A proxy = new AProxy();
B b = new BImpl(proxy);
A a = new AImpl(b);
proxy.setDelegate(a);
}