Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android(Java)中 this 關鍵字的用法詳解

編輯:Android 開發實例

在 Java 程式中經常能見到 this,自己也偶爾用到它,但到底 this 該怎麼用,卻常常心中沒底。很多人一提起它就說「當前物件」,可到底什麼是當前物件、是哪個當前物件,自己也說不清楚。以下就透過一個小範例,分享 Java 中 this 的三種用法。

範例程式碼

package eoe.demo;

/**
 * 本範例為了說明 this 的三種用法。
 */
public class ThisTest {
    private int i = 0;

    // 第一個建構子:有一個 int 型引參數
    ThisTest(int i) {
        this.i = i + 1; // 此時 this 表示引用成員變數 i,而非函式參數 i
        System.out.println("Int constructor i —— this.i: " + i + " —— " + this.i);
        System.out.println("i-1:" + (i - 1) + " this.i+1:" + (this.i + 1));
        // 從兩個輸出結果充分證明 i 和 this.i 是不一樣的!
    }

    // 第二個建構子:有一個 String 型引參數
    ThisTest(String s) {
        System.out.println("String constructor: " + s);
    }

    // 第三個建構子:有一個 int 型與一個 String 型引參數
    ThisTest(int i, String s) {
        this(s); // this 呼叫第二個建構子
        // this(i); // 此處不能用,因為只有建構子能呼叫建構子,
        // 且必須位於第一行,一次也只能呼叫一個建構子。
        this.i = i++; // this 用來引用該類別的成員變數
        System.out.println("Int constructor: " + i + "\n" + "String constructor: " + s);
    }

    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++,如此鏈式呼叫。
    }
}

this 的三種主要用法

  1. 表示對當前物件的引用。這是最根本的用法。
  2. 表示使用類別的成員變數,而非函式參數。特別是在函式參數與成員變數同名時用來區分——其實這是第一種用法的特例,因較常使用,特別拉出來強調。
  3. 在建構子中引用滿足指定參數型別的其他建構子(建構方法)。這裡必須非常注意:只能引用一個建構方法,且必須位於方法起始的第一行。

特別提醒

此外還有一點要注意:this 不能用在 static 方法中!因此甚至有人戲稱 static 方法的定義就是「沒有 this 的方法」。雖然略顯誇張,卻也充分說明了 this 無法在 static 方法裡使用的原因——因為 static 方法屬於類別本身,而非任何具體物件實例。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved