public class Test2 {
int i = 0;
Test2(int i) {
this.i = i;
}
Test2 increament() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Test2 t = new Test2(100);
t.increament().increament().print();
}
}
public class Test2 { 定义一个叫test2的类
int i = 0; 私有成员i
Test2(int i) {
this.i = i; 将作为参数的i传给私有成员的i,这是构造函数
}
Test2 increament() { 增加
i++; 私有成员i加1
return this; 返回自己,这样可以链式调用
}
void print() {
System.out.println("i = " + i); 输出i
}
public static void main(String[] args) {
Test2 t = new Test2(100); 创建了一个实例,i初始化为100
t.increament().increament().print(); 递增两次再输出,注意,之所以可以反复调用,是因为每次increament都返回了自身
}
}
要解说哪方面?具体点。
t.increament()
返回t本身,然后接着再次调用t.increament()
Test2 increament() 那这个Test2 是个类名 increament() 这个又是个方法 是什么回事?
----------------------------------构造函数----------------------------
Test2(int i) {
this.i = i;
}
---------------------------------------这个函数的关键在于返回了自己-----------------------
Test2 increament() { 增加
i++;
return this;
}