Create an object before calling super in java

Given that simple Java code does 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 calling super() , because I need to push it in the mom class.

I do not want to use the initialization block, and I do not want to do something like:

super(new Foo(bar)) in my constructor ..

How can I send data to the mother class before the super call?

+6
source share
3 answers

If Foo needs 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 legit for me, you can wrap new Foo(bar) in a static method if you want.

Also note that field initializers (as in your example) and initializer blocks will not help, because they are run after the constructor of the superclass. If the field is declared final , your example will not compile, otherwise you will get null in the constructor of the superclass.

+15
source

This is not possible in java. the only possible solution is a new challenge in the super constructor.

if the foo object can be shared between instances, you can declare it as static

 public class Bar extends AbstractBar{ private static final Foo foo = new Foo(bar); public Bar(){ super(foo); } } 

if the superclass is under your control, you can reorganize it and use the template method template to pull the object into the constructor instead of calling it from the subclass. this applies the hollywod principle: do not 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(); } } 
+1
source
 class AbstractBar{ public AbstractBar() { } public AbstractBar(Foo t) { } } class Bar extends AbstractBar{ static Foo t=null; public Bar() { super(t=new Foo()); } } class Foo{...} 
+1
source

Source: https://habr.com/ru/post/918490/


All Articles