public class Leaf {
private int i = 0;
Leaf increment()//这是个构造方法吗?怎么还有个increment?
{
i++;
return this;//想知道这个this指的是什么?
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();//这句怎么么运行?
}
private int i = 0;
Leaf increment()//这是个构造方法吗?怎么还有个increment?
{
i++;
return this;//想知道这个this指的是什么?
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();//这句怎么么运行?
}
{
i++;
return this;//想知道这个this指的是什么?
}
返回一个Leaf对象,i自增1
this就是调用increment方法的这个对象本身。
{
i++;
return this;//想知道这个this指的是什么?
}
这是一个很普通的方法。
那最后的i是多少?怎么远行?
返回leaf类型,这个类型就是x吗?
private int i = 0;
Leaf increment()// 这个不是构造方法,只是一个返回类型为 Leaf 的普通方法。
{
i++;
return this;// 这个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() 返回的是x ,该对象的属性i加一。往后类推!
}
x.increment();
x.increment();
x.increment();
x.print();