Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor init from another constructor with shared objects in their arguments

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?

like image 609
jscherman Avatar asked Feb 20 '26 03:02

jscherman


1 Answers

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.

like image 192
Elliott Frisch Avatar answered Feb 22 '26 17:02

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!