ver*_*ald 4 java constructor tostring
说我有一些课,比如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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望添加一个构造函数,该构造函数将表示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);
}
Run Code Online (Sandbox Code Playgroud)
但是,Java在调用this(x,y)之前不允许语句.是否有一些可接受的解决方法?
Yis*_*hai 10
由于这两个值,这种特殊情况有点尴尬,但你可以做的是调用静态方法.
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;
}
Run Code Online (Sandbox Code Playgroud)
话虽这么说,如果这个类不需要被子类化,那么将构造函数全部保密并且具有公共静态工厂方法会更清晰,更好,更具风格:
public static Foo createFoo(String xy) {
Integer x;
Integer y;
//etc.
return new Foo(x, y);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |