How to initialize a circular dependency (final fields referencing each other)?

前端 未结 3 483
轮回少年
轮回少年 2021-01-12 09:05

How do you initialize this:

class A {
    final B b;

    A(B b) {
        this.b = b;
    }
}

class B {
    final A a;

    B(A a) {
        this.a = a;
           


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 09:39

    You could use a factory method

    class A {
        final B b;
    
        A(B b) {
            this.b = b;
        }
    }
    
    abstract class B {
        final A a;
    
        B() {
            this.a = constructA();
        }
    
        protected abstract A constructA();
    }
    
    public class C {
        public static void main(String []args){
            new B(){
                protected A constructA(){
                    return new A(this);
                }
            };
        }
    }
    

提交回复
热议问题