所以,我有一个具有以下构造函数的类:
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;
}
现在,我想通过更改默认构造函数来重新利用第二个构造函数,例如:
public SomeClass() {
Foo = new Foo();
this(foo, new Bar(foo));
}
但这并不像我得到的那样工作
Error:(24, 21) java: call to this must be first statement in constructor
请注意,我不想有 2 个单独的 foo 实例。
有什么想法可以解决这个问题吗?
最佳答案
为了使用this
构造函数,它必须是构造函数的第一行。类似的东西,
public SomeClass() {
this(new Foo());
}
public SomeClass(Foo foo) {
this(foo, new Bar(foo));
}
注意:如果您想防止外部调用,您可以将SomeClass(Foo)
构造函数设为private
。
关于java - 从参数中包含共享对象的另一个构造函数调用构造函数 init,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58838957/