日期:2014-05-20  浏览次数:20677 次

在看this时遇到问题,希望大家给出解释
public class Leaf{
 int i;
 Leaf(int i){this.i = i;
  }
 Leaf increament(){
  i++;
  return this;
 }
 void print(){
 System.out.println("i = "+i);
  }
 public static void main(String[] args){
  Leaf leaf = new Leaf(8);
  leaf.intcreament().intcreament().print();//这句是什么意思??
 }
}


------解决方案--------------------
探讨
this指代当前对象,也就是Leaf
return this; 返回的就是一个Leaf对象
leaf.intcreament().intcreament().print();
leaf.intcreament() 此时返回的是一个Leaf对象 此时调用了一个构造方法 i = 8 + 1
leaf.intcreament().intcreament() 在上一步的基础上再调用一次intcre……