java - 从另一个构造函数调用构造函数 init,其参数中包含共享对象
问题描述
所以,我有一个具有以下构造函数的类:
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
推荐阅读
- json - 如何在 Kotlin 中忽略(跳过反序列化)格式错误的 LocalDate 字段?
- mysql - where子句如何处理元组
- dialogflow-es - 为什么取消关联帐户后,仍会存储身份验证凭据?
- javascript - 如何将 javascript 变量添加到 javascript src。使用 jQuery
- reactjs - 如何在不覆盖 React 中其他项目的情况下设置对象的状态
- powershell - 使用 Powershell 在 Windows 中闪烁 SAS 磁盘盒中的灯
- reactjs - 尽管使用反应嵌套提取,但迭代数组不适用于数据
- flutter - 我无法序列化 Flutter 中带有下划线的数据
- arrays - 在 VBA 中对数组运行计算 - 跨列
- airflow - 是否有可能(也是一个好主意)根据数据库的结果动态创建 Airflow dag?