这就是我想要做的(在Java 1.6中):
public class Foo {
public Foo() {
Bar b = new Bar();
b.setSomeData();
b.doSomethingElse();
this(b);
}
public Foo(Bar b) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
编译说:
call to this must be first statement in constructor
Run Code Online (Sandbox Code Playgroud)
有没有解决方法?
Ste*_*n C 18
你可以像这样实现它:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
该makeBar方法应该是静态的,因为在this您调用方法时,对应的对象不可用.
顺便说一下,这种方法的优点是它确实将完全初始化的Bar对象传递给了Foo(Bar).(@RonU注意到他的方法没有.这当然意味着他的Foo(Bar)构造函数不能假设它的Foo参数处于最终状态.这可能是有问题的.)
最后,我同意静态工厂方法是这种方法的一个很好的替代方法.
您可以将"默认构造函数"实现为静态工厂方法:
public class Foo {
public static Foo createFooWithDefaultBar() {
Bar b = new Bar();
b.setSomeData();
b.doSomethingElse();
return new Foo(b);
}
public Foo(Bar b) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1746 次 |
| 最近记录: |