当前位置: 技术问答>java相关
java的初学问题,关于this关键字的问题,谢谢各位了,先来的就先得了:)
来源: 互联网 发布时间:2015-04-04
本文导语: public class Leaf { private 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.incre...
public class Leaf {
private 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();
}
} ///:~
这个x.increment().increment().increment().print();
为什么要用那么重复的increment()?:(
private 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();
}
} ///:~
这个x.increment().increment().increment().print();
为什么要用那么重复的increment()?:(
|
increment() return this, which is the handle to the current object,
so the return value of x.increment() is x
x.increment().increment().increment().print();
is equivalent to
(((x.increment()).increment()).increment()).print();
//after i is incremented
===>((x.increment()).increment()).print();
//after i is incremented
===>(x.increment()).print();
//after i is incremented
==>x.print();
so the return value of x.increment() is x
x.increment().increment().increment().print();
is equivalent to
(((x.increment()).increment()).increment()).print();
//after i is incremented
===>((x.increment()).increment()).print();
//after i is incremented
===>(x.increment()).print();
//after i is incremented
==>x.print();
|
无论用多少个increment(),返回的都是x对象,这个例子很好的说明了this的特性
|
写那么多increment只不过是为了增加i的值而已
打印的结果应该是i=3
打印的结果应该是i=3