public class A {
String s = "Hello";
public A(String s) {
System.out.println("參數 s = " + s); // 參數
System.out.println("成員 this.s = " + this.s); // 成員
this.s = s; // 賦值給成員
}
}
this.s 明確指向「當前物件的成員 s」,解決遮蔽問題。
public class A {
public A() { new B(this).print(); }
public void print() { System.out.println("Hello from A!"); }
}
public class B {
A a;
public B(A a) { this.a = a; }
public void print() { a.print(); System.out.println("Hello from B!"); }
}
new B(this) 將 A 實例傳給 B,實現回調或協作。
public class A {
int i = 1;
public A() {
new Thread() {
public void run() {
for (;;) {
A.this.run(); // 必須用 外部類名.this
sleep(1000);
}
}
}.start();
}
public void run() { System.out.println("i = " + i++); }
}
匿名類 Thread 內的 this 指向匿名類自身,若同名方法需呼叫外部類,必須用 外部類名.this.方法()。