问题描述
我使用复合类来对功能进行分组。
但是,A类(带有复合A1)由B继承(使用复合B1),并且A1中存在的行为将被调整在B1,但最终的a1必须是一个B1实例才能工作。
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 adapted at B1, but the final a1 must be a B1 instance for this to work.
Obs。:我有以确保复合实例化正确发生(仅由其复合伙伴)。
Obs.: I have ways to make sure the composite instantiation happens properly (only by its composite partner).
无法将B1对象分配给a1 final field:
Unable to assign a B1 object to a1 final field:
class finalFieldTestFails{
class A1{
A1(A a){}
}
class A{
protected final A1 a1;
A(){
this.a1 = new A1(this);
}
A(A1 a1){
this.a1 = a1;
}
}
class B1 extends A1{
B1(B b){
super(b);
}
}
class B extends A{
//B(){ super.a1=new B1(this); } //FAIL: cant change final value
//B(){super(new B1(this));} //FAIL: cant use 'this' or 'super'
}
}
PS:如果可能,答案不应包含反射安全技巧。
PS.: the answer shall not involve reflection security tricks if possible.
推荐答案
,我发现这个我在下面输入了这段代码。
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.
所以我最终使用重写方法来实例化1类型,让超级班负责任务。
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。:其他提示/解决方法将不胜感激。
PS.: Other tips/workarounds will be appreciated.
这篇关于复合继承:如何在子类构造函数中分配一个最终字段,该字段取决于'this'值(向后引用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!