This is what I’m 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) {
// ...
}
}
Compiler says:
call to this must be first statement in constructor
Is there any workaround?
You could implement it like this:
The
makeBarmethod should be static, since the object corresponding tothisis not available at the point you are calling the method.By the way, this approach has the advantage that it does pass a fully initialized
Barobject to theFoo(Bar). (@RonU notes that his approach does not. That of course means that hisFoo(Bar)constructor cannot assume that itsFooargument is in its final state. This can be problematical.)Finally, I agree that a static factory method is a good alternative to this approach.