Say I have some class, e.g. 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;
}
}
Now, I wish to add a constructor which takes as its argument a string representing a Foo, e.g. Foo("1 2") would construct a Foo with x=1 and y=2. Since I don't want to duplicate the logic in the original constructor, I would like to be able to do something like this:
public Foo(string stringRepresentation) {
Integer x;
Integer y;
// ...
// Process the string here to get the values of x and y.
// ...
this(x, y);
}
However, Java does not allow statements before the call to this(x, y). Is there some accepted way of working around this?