Frage

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 ?

War es hilfreich?

Lösung

If Foo has to be stored in a field, you can do this:

public class Bar extends AbstractBar{    
    private final Foo foo;

    private Bar(Foo foo) {
        super(foo);
        this.foo = foo;
    }

    public Bar(){
        this(new Foo(bar));
    }
}

Otherwise super(new Foo(bar)) looks pretty legal for me, you can wrap new Foo(bar) into a static 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 get null in superclass constructor.

Andere Tipps

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

public class Bar extends AbstractBar{

    private static final Foo foo = new Foo(bar);

    public Bar(){
        super(foo);
    }
}

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 ;)

public abstract class AbstractBar{

    private Object thing;

    public AbstractBar(){
         this.thing = this.createThatThing();            
    }

    protected abstract Object createThatThing();
}

public class Bar extends AbstractBar {

     // no constructor needed

     protected Object createThatThing(){
          return new Thing();
     }
}
class AbstractBar{
    public AbstractBar() {
    }
    public AbstractBar(Foo t) {
    }
}
class Bar extends AbstractBar{
    static Foo t=null;
    public Bar() {
        super(t=new Foo());
    }
}
class Foo{...}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top