How to implement constructor packaging in Java?

This is what I am trying to do (in Java 1.6):

public class Foo {
  public Foo() {
    Bar b = new Bar();
    b.setSomeData();
    b.doSomethingElse();
    this(b);
  }
  public Foo(Bar b) {
    // ...
  }
}

The compiler says:

call to this must be first statement in constructor

Is there a workaround?

+5
source share
3 answers

You need to implement it as follows:

public class Foo {
  public Foo() {
    this(makeBar());
  }
  public Foo(Bar b) {
    // ...
  }
  private static Bar makeBar() {
    Bar b = new Bar();
    b.setSomeData();
    b.doSomethingElse();
    return b;
  }
}

The method makeBarmust be static, because the object corresponding to thisit is not available at the point that you call the method.

By the way, this approach has the advantage that it passes a fully initialized object Barto Foo(Bar). (@RonU notes that his approach does not do this. This, of course, means that his constructor Foo(Bar)cannot assume that his argument Foois in the final state. This may be problematic.)

, , factory .

+17

" " factory:

public class Foo {
  public static Foo createFooWithDefaultBar() {
    Bar b = new Bar();
    b.setSomeData();
    b.doSomethingElse();
    return new Foo(b);
  }
  public Foo(Bar b) {
    // ...
  }
}
+5

As the saying goes, calling this () should be the first thing that should happen in the constructor. Is there a reason this will not work?

public class Foo {
  public Foo() {
    this(new Bar());
    Bar b = getBar();
    b.setSomeData();
    b.doSomethingElse();
  }
  public Foo(Bar b) {
    // ...
  }
}
-1
source

All Articles