たとえば、Fooなどのクラスがあるとします。
public class Foo {
private Integer x;
private Integer y;
public Foo(Integer x, Integer y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
}
ここで、Fooを表す文字列を引数として取るコンストラクターを追加したいと思います。たとえば、Foo( "1 2")はx=1およびy=2のFooを作成します。元のコンストラクターのロジックを複製したくないので、次のようなことができるようにしたいと思います。
public Foo(string stringRepresentation) {
Integer x;
Integer y;
// ...
// Process the string here to get the values of x and y.
// ...
this(x, y);
}
ただし、Javaでは、this(x、y)を呼び出す前のステートメントは許可されていません。これを回避するための受け入れられた方法はありますか?