Say I have two classes like this
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;
}
}
I want to make a subclass of Foo
, Foo2
, which has as its child a Bar2
, which is a subclass of Bar
. I can do it like this:
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);
}
}
However, this is supposed to be a very bad idea. But something like this won't work:
public class Foo
{
protected final Bar child;
public Foo()
{
this(new Bar(this));
}
protected Foo(Bar child)
{
this.child = child;
}
}
because new Bar(this)
refers to this
before the supertype constructor has been called.
I see two means for dealing with this:
1) I could make the members private and non-final, and then make setters which throw an exception if they're already set, but that seems clumsy and only detects any coding problems at runtime.
2) I make the Foo
constructor take as a parameter the Class
object for the type of Bar
to use, and then use reflection to invoke that class's constructor. However, that seems heavyweight for what I'm trying to do.
Is there any coding technique or design pattern I'm missing?