return this的用法

来源:互联网 发布:火爆网络女神雅典娜 编辑:程序博客网 时间:2024/05/19 10:55

 每次返回类实例,用return this;

 

  1. class Test2 {
  2. String s="";
  3. public static void main(String[] args) {
  4.    Test2 t = new Test2();
  5.    t.method("111");
  6.    t.method("222");
  7.    t.method("333");
  8.    t.method2();
  9. }
  10. public Test2 method(String sb) {
  11.    s+=sb;
  12.    return this;
  13. }
  14. public void method2() {
  15.   
  16.    System.out.println(s);
  17. }
  18. }

 结果: 111222333

 

  1. class Test 
  2. public static void main(String[] args) 
  3. Test t = new Test().method();//返回当前这个类的实例给t 
  4. t.method2(); 
  5. public Test method() 
  6. return this
  7. public void method2() 
  8. System.out.println( "Hello Beijing 2008! "); 

return this就是返回当前这个类的一个实例 this 就是代表当前这个类的一个实例.


 原文参考:

http://hi.baidu.com/rague/blog/item/5a44a882a0d1afa70cf4d2b9.html