假设我有一些课程,例如 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) 之前使用语句。有一些公认的解决方法吗?