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?
The two rules for creating a constructor are: The name of the constructor should be the same as the class. A Java constructor must not have a return type. Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.
In Java, a constructor can be overloaded as a feature, of object-oriented programming. Whenever multiple constructors are needed, they are implemented as overloaded methods. It allows more than one constructor inside the class, with a different signature.
The only way to create new Wrapper objects is to use their valueOf() static methods. For example for Integer objects, Integer. valueOf implements a cache for the values between -128 and 127 and returns the same reference every time you call it.
You could implement it like this:
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 makeBar
method should be static, since the object corresponding to this
is 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 Bar
object to the Foo(Bar)
. (@RonU notes that his approach does not. That of course means that his Foo(Bar)
constructor cannot assume that its Foo
argument is in its final state. This can be problematical.)
Finally, I agree that a static factory method is a good alternative to this approach.
You can implement the "default constructor" as a static factory method:
public class Foo {
public static Foo createFooWithDefaultBar() {
Bar b = new Bar();
b.setSomeData();
b.doSomethingElse();
return new Foo(b);
}
public Foo(Bar b) {
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With