this主要要三种用法: 1、表示对当前对象的引用! 2、表示用类的成员变量,而非函数参数,注意在函数参数和成员变量同名是进行区分!其实这是第一种用法的特例,比较常用,所以那出来强调一下。 3、用于在构造方法中引用满足指定参数类型的构造器(其实也就是构造方法)。但是这里必须非常注意:只能引用一个构造方法且必须位于开始! 还有就是注意:this不能用在static方法中!所以甚至有人给static方法的定义就是:没有this的方法!虽然夸张,但是却充分说明this不能在static方法中使用!
public class ThisTest {
private int i = 0;
ThisTest(int i){
this.i=i+1;
System.out.println("Int constructor i——this.i: "+i+"——"+this.i); //11
System.out.println("i-1:"+(i-1)+"this.i+1:"+(this.i+1)); //9 12
}
ThisTest(String s){
System.out.println("String constructor: "+s); //ok
}
ThisTest(int i,String s){
this(s);//this调用第二个构造器 //ok again!
// this(i);
/*此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用他。
但是必须注意:就算是构造方法调用构造器,也必须为于其第一行,构造方法也只能调
用一个且仅一次构造器!*/
this.i=i++;//this以引用该类的成员变量 21
System.out.println("Int constructor: "+i+"/n"+"String constructor: "+s);//21 ok again
}
public ThisTest increment(){
this.i++;
return this;//返回的是当前的对象,该对象属于(ThisTest)
}
public static void main(String[] args){
ThisTest tt0=new ThisTest(10);
ThisTest tt1=new ThisTest("ok");
ThisTest tt2=new ThisTest(20,"ok again!");
System.out.println(tt0.increment().increment().increment().i);
//tt0.increment()返回一个在tt0基础上i++的ThisTest对象,
//接着又返回在上面返回的对象基础上i++的ThisTest对象!
}
}
http://blog.csdn.net/fzfengzhi/article/details/2174406