use*_*642 7 java constructor this
this在java中构造对象时,可以作为参数传递给方法吗?
考虑这样做会让我感到不安,但我不确定这是不是错了.采用以下假设示例:
public final class A {
private final B b;
private final List<String> words;
public A(B b) {
this.b = b;
words = new ArrayList<String>();
for(int i = 0; i < 10; i++) {
words.add(b.getNextStringFromUser(this));
}
}
public List<String> getWords() {
return words;
}
}
public class B {
// returns a String chosen by the user based on the current state of A
public String getNextStringFromUser(A a) {
List<String> wordsSoFar = a.getWords();
// ... omitted
}
}
Run Code Online (Sandbox Code Playgroud)
我可以想到这样做的情况可能是正确的事情,你想要构建一个对象,从其他代码的角度来看,它可以是不可变的,但是构造函数可能会采用不同的方法.在目前为止指定的状态(如果谈论部分构造的对象的状态是有意义的).在上面的示例中,用户根据到目前为止选择的字符串选择一个字符串,当它们全部被选中时,该对象永远不会再次更改.
这种事情好吗/可取吗?谢谢.
在java中构造对象时作为方法的参数?
我愿意think twice,因为你的object is not even constructed fully。
它可能有一些attributes which are still null or unitialized.,如果其他类访问这些属性,这些属性将为空,请做好准备NULL POINTER EXCEPTIONS。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
737 次 |
| 最近记录: |