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

≡放荡痞女 提交于 2019-12-02 07:06:20

B(){ super.a1=new B1(this); } //FAIL: cant change final value

You can not assign values to already assigned final variables, You can instantiate it within the constructor but not as following.

B(){super(new B1(this));} //FAIL: cant use 'this' or 'super'

You can use this once the instance is created only. Since there is a inheritance tree, it is not completely instantiated, So the compiler complains,

cannot reference this before supertype constructor has been called

Aquarius Power

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!