this 是 Java 中的一個隱含參數,代表「正在呼叫該方法的當前物件實例」。編譯器在非靜態方法中隱式傳遞 this 參考,使方法能存取呼叫者的欄位與方法。
class Banana {
void f(int i) { /* 方法體 */ }
}
Banana a = new Banana();
Banana b = new Banana();
a.f(1);
b.f(2);
// 編譯器實際轉換為:
Banana.f(a, 1); // this = a
Banana.f(b, 2); // this = b
public class Person {
private String name;
public void setName(String name) {
this.name = name; // this.name 為實例變數,name 為參數
}
}
public class Book {
private String title;
private String author;
private int pages;
public Book(String title) {
this(title, "佚名"); // 呼叫另一建構子
}
public Book(String title, String author) {
this(title, author, 0);
}
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
}
public class Config {
private String host;
private int port;
private boolean ssl;
public Config setHost(String host) { this.host = host; return this; }
public Config setPort(int port) { this.port = port; return this; }
public Config setSsl(boolean ssl) { this.ssl = ssl; return this; }
// 使用:new Config().setHost("localhost").setPort(8080).setSsl(true);
}
public class EventManager {
public void register(Listener listener) { ... }
}
public class MyComponent {
private EventManager manager;
public void init() {
manager.register(this); // 將自身作為監聽器註冊
}
}
public class Outer {
private String value = "Outer";
class Inner {
public void print() {
System.out.println(Outer.this.value); // 明確指定外部類實例
}
}
}
public class Leaf {
private int i = 0;
public Leaf increment() {
i++;
return this; // 返回當前物件
}
public void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print(); // 輸出: i = 3
}
}
this = new Object() 編譯錯誤。每個物件實例在堆記憶體中包含:
this 實際上就是指向該物件堆記憶體起始位址的參考 (Reference),在 64 位 JVM 中通常為 64 位指標 (開啟壓縮指標則為 32 位)。