java之this關鍵字

高傑才_Android發表於2014-09-27

this使用範圍  

1、在類的方法定義中使用的this關鍵字代表呼叫該方法物件的引用。

2、當必須指出當前使用方法的物件是誰時,要使用關鍵字this。

3、有時使用this可以處理方法中成員變數和引數重名的情況。

4、this可以看做是一個變數,它的值是當前物件的引用

注:this一般出現在方法中,當方法沒有被呼叫時。並不知道this指向那個具體的物件。

當某個物件呼叫有this的方法時,this就指向呼叫這個方法的物件。

程式code:

public class TestThis{
    private int i;
    public TestThis(int i){
        this.i = i;
    }
    private TestThis increment(){
        i += 1;
        return this;
    }
    
    public static void main (String[] args){
        TestThis mTestThis = new TestThis(100);
        System.out.println(mTestThis.increment().increment().i);
    }
}

輸出結果:102

相關文章