composite inheritance: how to assign a final field at sub-class constructor which depends on 'this' value (backward reference)?

后端 未结 2 1623
南笙
南笙 2021-01-25 16:05

I use composite classes to group functionalities.
But, the class A (with composite A1), got inherited by B (with composite B1), and a behavior existent at A1 is going to be

2条回答
  •  無奈伤痛
    2021-01-25 16:32

    With this tip, given by @KevinHooke, I found this answer and I came with this code below.

    But be aware that this option I chose may cause trouble.

    So I ended up using an overriden method to instantiate the "1" kind, letting the super class take care of the assignment.

    class finalFieldTestWorks{
        class A1{A1(A a){}}
    
        class A{
          protected final A1 a1;
          A(){
            this.a1=new1();
          }
          protected A1 new1(){return new A1(this);}
        }
    
        class B1 extends A1{B1(B b){super(b);}}
    
        class B extends A{
          B(){
            super();
          }
          @Override
          protected B1 new1(){return new B1(this);}
        }
    }
    

    PS.: Other tips/workarounds will be appreciated.

提交回复
热议问题