public class Leaf {
private int i = 0;
Leaf increment() {
i++;
return this ;//this 在这里是什么意思,如果将this替换成this.increment()
//运行就会抛出异常,如果替换成new Leaf(),则最后打印出来的i还是为0
//这是什么原因,另外象这种 Leaf increment() 方法表示什么含义,与一般
//方法有什么区别,谢谢解答
}
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() {
i++;
return this ;//this 在这里是什么意思,如果将this替换成this.increment()
//运行就会抛出异常,如果替换成new Leaf(),则最后打印出来的i还是为0
//这是什么原因,另外象这种 Leaf increment() 方法表示什么含义,与一般
//方法有什么区别,谢谢解答
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
} ///
因为默认构造是i=0;
-- 那就成了死循环了,最终会因为超过int的最大值而抛出异常;
如果替换成new Leaf()
--不过是创建了另外一个实例,初始值当然为0
------------
this 指的就是对当前对象的引用,你可以结合super理解下
new Leaf().increment().increment().increment().increment();看上去要比
Leaf l = new Leaf();
l.increment();
.increment();
.increment();
.increment();
看起来简洁。
如果替换成new Leaf()--不过是创建了另外一个实例,初始值当然为0。public class Leaf {
private int i = 0;
//Leaf(){} //
Leaf increment() {
i++;
System.out.println(i); //在这里就可看出i有增加。
//return this ;//this 在这里是什么意思,如果将this替换成this.increment()
return new Leaf(); //运行就会抛出异常,如果替换成new Leaf(),则最后打印出来的i还是为0
//这是什么原因,另外象这种 Leaf increment() 方法表示什么含义,与一般
//方法有什么区别,谢谢解答
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
} ///
this就是当前所在类,即public class Leaf中的Leaf,就是class Leaf的一个reference
-- 那就成了死循环了,最终会因为超过int的最大值而抛出异常;
如果替换成new Leaf()
--不过是创建了另外一个实例,初始值当然为0
------------
this 指的就是对当前对象的引用,你可以结合super理解下
这里的意思也就是让这个对象的i增加1后再返回这个对象的引用;
第二:你改为new Leaf()后,每次调用increment() 方法都返回了一个新的对象引用,而它的i初始 值就是0的;所以最后结果是0。
不知道我的解答有没有问题,楼主你自己考虑吧,呵呵
不知道我的解答有没有问题,楼主你自己考虑吧,呵呵