当前位置: 代码迷 >> J2SE >> 在看this时遇到有关问题,希望大家给出解释
  详细解决方案

在看this时遇到有关问题,希望大家给出解释

热度:22   发布时间:2016-04-24 12:25:38.0
在看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……
  相关解决方案