this的用法

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/2174406this

相關文章
相關標籤/搜索