【发布时间】:2010-03-04 03:39:55
【问题描述】:
假设我有一些课,例如福:
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) 之前使用语句。有一些公认的解决方法吗?
【问题讨论】:
-
为什么一定要叫这个(x, y)?为什么不直接设置 x 和 y?
-
正如我在原始问题中提到的,我希望避免在现有构造函数中重复逻辑。例如,我想稍后添加某种验证,然后我只需要修改原始构造函数而不是两者。
标签: java constructor tostring