每次返回类实例,用return this;
- class Test2 {
- String s="";
- public static void main(String[] args) {
- Test2 t = new Test2();
- t.method("111");
- t.method("222");
- t.method("333");
- t.method2();
- }
- public Test2 method(String sb) {
- s+=sb;
- return this;
- }
- public void method2() {
- System.out.println(s);
- }
- }
结果: 111222333
- class Test
- {
- public static void main(String[] args)
- {
- Test t = new Test().method();//返回当前这个类的实例给t
- t.method2();
- }
- public Test method()
- {
- return this;
- }
- public void method2()
- {
- System.out.println( "Hello Beijing 2008! ");
- }
- }
return this就是返回当前这个类的一个实例 this 就是代表当前这个类的一个实例.
原文参考:
http://hi.baidu.com/rague/blog/item/5a44a882a0d1afa70cf4d2b9.html