Without changing any of your types, this should work:
class ClassB {
ClassB() {
AtomicReference<A> ref = new AtomicReference<>(); // holder for instance
ClassA a = new ClassA(() -> ref.get().foo());
ref.set(a);
}
}
But you cannot invoke your lambda (Runnable#run) in your constructor, because a still has the value null. Only after the constructor has completed, the value is assigned.
Another possibility could be using a Consumer instead of a Runnable:
class ClassB {
ClassB() {
ClassA a = new ClassA(that -> that.foo()); // or maybe even: A::foo
}
}
class ClassA {
ClassA(Consumer<A> onChange) {
}
public void foo() {
System.out.println("Hello");
}
}
// call outside of `A`:
consumer.accept(a);
// or, inside of `A`:
consumer.accept(this);
Without seeing the rest of the code, it is difficult to give a good solution.
ais unused, andonChangeis unused.foo()method inside of theClassAconstructor implementation?setOnChangemethod. Anyway, you need to come up with a minimal reproducible example. Right now your code does nothing, so one way to fix it, while maintaining the behaviour (doing nothing) is to just remove the line with the error. Hopefully you see why this question is too broad.