views:

97

answers:

4

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?

+10  A: 

This particular case is kind of awkward because of the two values, but what you can do is call a static method.

  public Foo(Integer x, Integer y) {
      this(new Integer[]{x, y});
  }

  public Foo(String xy) {
      this(convertStringToIntegers(xy));
  }

  private Foo(Integer[] xy) {
      this.x = xy[0];
      this.y = xy[1];
  }

  private static Integer[] convertStringToIntegers(String xy) {
      Integer[] result;
      //Do what you have to do...
      return result;
  }

That being said, if this class doesn't need to be subclassed, it would be clearer and better and more idomatic to leave the constructors all private and have a public static factory method:

  public static Foo createFoo(String xy) {
       Integer x;
       Integer y;
        //etc.
        return new Foo(x, y);
  }
Yishai
The second option is exactly what I was looking for. Thanks!
veredesmarald
+1  A: 

Create a method that does takes care of the initialization required in both constructors and call that instead of this(...).

user144182
+4  A: 

Anothe option would be, you can think of having a static factory method that takes a String argument and returns an instance of Foo. This is similar to the approach used by valueOf(String s) method in Integer class.

sateesh
+1 Factory methods are definitely a good solution to working around many of the inflexibilities of constructors.
Chris Jester-Young
A: 

the first question that comes to mind about this is, why would even want to that? why is there a need to that? just a thought!

ultrajohn
the variables are coming from a web service or a file and he need to parse then construct?
medopal