this指針
參考:http://www.cnblogs.com/-cyb/articles/Java-this.html
作用1:當成員函數中局部變量a與成員變量a命名相同時,在成員函數中用this.a代表的是成員變量。
作用2:在類中調用成員函數時,用this,例如
class test{
void work(){}
void name(){
this.work();
}
}
作用3:在構造方法中調用另一個構造方法。
class test{
private int a;
//構造函數必須與類同名
test(){
this(3);//調用一個參數的構造函數,並且必須放在第一行,所以構造函數內只有一個this
//this(3,4);//因爲有了上面的this,不能再有這句了
}
test(int a){//構造函數可以有多個,但必須有不同的地方,和重載類似
this.a=a;
}
test(int a,int b){//又是另一個構造函數
a=b;
this.a=a;
}
作用4:特殊的一種用法return this。返回當前的對象的引用
//定義一個類
class test{
test setname(){
system.out.println(1);
return this;//返回當前對象的引用
}
}
//main函數
public class main {
public static void main(String[] args) {
test s1 = new test();//這裏創建的對象,也就是當前對象
test a=s1.work();//這樣a也指向s1這個對象了。
system.out.println(s1==a);//結果是true
//其實這種return的正確用法是:
s1.work().work().work();
//正因爲返回的是對象的引用,所以就像一個對象一樣,可以繼續.
//在Stringbuilder中,s2.append("").append("");正是這種用法
}
}