Considering that simple java code which would not work:
public class Bar extends AbstractBar{
private final Foo foo = new Foo(bar);
public Bar(){
super(foo);
}
}
I need to create an object before the super()
call because I need to push it in the mother class.
I don't want to use an initialization block and I don't want to do something like:
super(new Foo(bar))
in my constructor..
How can I send data to a mother class before the super call ?
thats not possible in java. the only possible solution is the new call in the super constructor.
if the foo object can be shared between instances you may declar it as static
if the super class is under your control, you can refactor it and use the template method pattern to pull the object into the constructor instead of pusing it from the subclass. this applys the hollywod principle: don't call us, we will call you ;)
If
Foo
has to be stored in a field, you can do this:Otherwise
super(new Foo(bar))
looks pretty legal for me, you can wrapnew Foo(bar)
into astatic
method if you want.Also note that field initializers (as in your example) and initializer blocks won't help either, because they run after the superclass constructor. If field is declared as
final
your example won't compile, otherwise you'll getnull
in superclass constructor.