So, I have a class with the following constructors:
public SomeClass() {
this.foo = new Foo();
this.bar = new Bar(foo); // Bar construction requires foo
}
public SomeClass(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
Now, I would like to reutilize the second constructor by changing the default constructor for something like:
public SomeClass() {
Foo = new Foo();
this(foo, new Bar(foo));
}
But this doesn't work as I'm getting
Error:(24, 21) java: call to this must be first statement in constructor
Note that I don't want to have 2 separate instances of foo.
Any ideas how to solve this scenario?
In order to use a this constructor, it must be the first line of the constructor. Something like,
public SomeClass() {
this(new Foo());
}
public SomeClass(Foo foo) {
this(foo, new Bar(foo));
}
Note: You can make the SomeClass(Foo) constructor private if you want to prevent outside calls.
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