Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create an object before the super call in java

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 ?

like image 719
Pier-Alexandre Bouchard Avatar asked Jun 19 '12 15:06

Pier-Alexandre Bouchard


3 Answers

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.

like image 150
axtavt Avatar answered Sep 21 '22 20:09

axtavt


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();
     }
}
like image 25
room13 Avatar answered Sep 19 '22 20:09

room13


class AbstractBar{
    public AbstractBar() {
    }
    public AbstractBar(Foo t) {
    }
}
class Bar extends AbstractBar{
    static Foo t=null;
    public Bar() {
        super(t=new Foo());
    }
}
class Foo{...}
like image 36
Subhrajyoti Majumder Avatar answered Sep 20 '22 20:09

Subhrajyoti Majumder