我正在阅读“用Java思考”,并在解释this
关键字的段落中,作者使用以下示例
public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
}
我想知道的是,如何理解
increment()
方法返回的内容?作者解释说,它返回对当前对象的引用。这是否意味着语句x.increment()
返回一种x
(我知道引用的含义)?在执行第一个x.increment().increment().increment().print();
之后,开始语句x.increment()
变成了x.increment().increment().print();
吗?这对我来说听起来合乎逻辑,但是我不确定我是否理解正确。
最佳答案
return this
返回当前实例,如果您想继续对其应用更改,这将非常方便。
来自JDK的一个很好的例子是StringBuilder
。例如,此代码没有任何错误:
StringBuilder builder = new StringBuilder();
builder.append("welcome");
builder.append("to");
builder.append("StackOverflow");
但这看起来好多了吗?
StringBuilder builder = new StringBuilder().append("welcome").append("to").append("StackOverflow");
关于java - 使用“return this”时如何了解返回的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27726632/