2. 把this作為參數傳遞 當你要把自己作為參數傳遞給別的對象時,也可以用this。如: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() {print();System.out.println("Hello from B!");}} 運行結果:Hello from A!Hello from B! 在這個例子中,對象A的建構函式中,用new B(this)把對象A自己作為參數傳遞給了對象B的建構函式。
3. 注意匿名類和內部類中的中的this。 有時候,我們會用到一些內部類和匿名類。當在匿名類中用this時,這個this則指的是匿名類或內部類本身。這時如果我們要使用外部類的方法和變數的話,則應該加上外部類的類名。如下面這個例子:public class A {int i = 1;public A() {Thread thread = new Thread() {public void run() {for(;;) {A.this.run();try {sleep(1000);} catch(InterruptedException ie) {}}}};thread.start();}
public void run() {System.out.println("i = " + i);i++;}
public static void main(String[] args) throws Exception {new A();}