このような2つのクラスがあるとします
public class Foo
{
protected final Bar child;
public Foo()
{
child = new Bar(this);
}
}
public class Bar
{
protected final Foo parent;
public Bar(Foo parent)
{
this.parent = parent;
}
}
Foo
のサブクラスである をFoo2
子として持つのサブクラスを作成したいと考えています。私はこのようにすることができます:Bar2
Bar
public class Foo
{
protected final Bar child;
public Foo()
{
child = new makeChild();
}
protected Bar makeChild()
{
return new Bar(this);
}
}
public class Foo2 extends Foo
{
@Override
protected Bar makeChild()
{
return new Bar2(this);
}
}
しかし、これは非常に悪い考えです。しかし、このようなものはうまくいきません:
public class Foo
{
protected final Bar child;
public Foo()
{
this(new Bar(this));
}
protected Foo(Bar child)
{
this.child = child;
}
}
スーパータイプコンストラクターが呼び出される前にnew Bar(this)
参照するためです。this
これに対処するには、次の 2 つの方法があります。
1) メンバーをプライベートで非最終的なものにしてから、既に設定されている場合に例外をスローするセッターを作成できますが、それは不器用に思え、実行時にコーディングの問題のみを検出します。
2)コンストラクターが使用する型のオブジェクトをFoo
パラメーターとして取り、リフレクションを使用してそのクラスのコンストラクターを呼び出します。しかし、それは私がやろうとしていることにとっては重いようです。Class
Bar
不足しているコーディング手法やデザインパターンはありますか?