javasuperclass

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 base 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 base class before the super call ?


Solution

  • 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.