跳轉到內容

Java 程式設計/關鍵字/this

來自華夏公益教科書,開放的書籍,為一個開放的世界

this 是一個 Java 關鍵字。它包含當前物件的引用。

  1. 解決例項變數和引數之間的歧義。
  2. 用於將當前物件作為引數傳遞給另一個方法。

語法

this.method();
or
this.variable;

示例 #1 用於情況 1

Computer code
public class MyClass
 { 
    //...
    private String value;
    //...
    public void setMemberVar( String value )
    {
        this.value= value;
    }
 }

示例 #2 用於情況 1

Computer code
public class MyClass
 { 
    MyClass(int a, int b) {
        System.out.println("int a: " + a);
        System.out.println("int b: " + b);
    }
    MyClass(int a) {
        this(a, 0);
    }
    //...
    public static void main(String[] args) {
        new MyClass(1, 2);
        new MyClass(5);
    }
 }
華夏公益教科書