Best way to add a string constructor to a Java class?

Say I have a class, for example. 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 want to add a constructor that takes as argument an string representing Foo, for example. Foo ("1 2") would build Foo with x = 1 and y = 2. Since I don't want to duplicate the logic in the original constructor, I would like 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 calling this (x, y). Is there an accepted way around this?

+4
source share
3 answers

This particular case is awkward due to two meanings, but what you can do is call the 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; } 

Moreover, if this class does not need a subclass, it would be clearer and better and more explicit in order 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); } 
+10
source

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

+4
source

Create a method that performs the initialization required by both constructors, and call (...) instead.

+1
source

Source: https://habr.com/ru/post/1303077/


All Articles