標籤:
1. this是指當前對象自己。
用類名定義一個變數的時候,定義的應該只是一個引用,外面可以通過這個引用來訪問這個類裡面的屬性和方法,那們類裡面是夠也應該有一個引用來訪問自己的屬性和方法納?呵呵,JAVA提供了一個很好的東西,就是 this 對象,它可以在類裡面來引用這個類的屬性和方法。如下面這個例子中:
public class ThisDemo {String name = "Mick";public void print(String name) {System.out.println("類中的屬性 name=" + this.name);System.out.println("局部傳參的屬性=" + name);}public static void main(String[] args) {ThisDemo tt = new ThisDemo();tt.print("Orson");}}
2.使用this區分同名變數
成員變數與方法內部的變數重名時,希望在方法內部調用成員變數,怎麼辦呢?這時候只能使用this,例如:
public class Demo {public String name;public int age;public Demo(String name, int age) {this.name = name;this.age = age;}public void say() {System.out.println(name + " " + age);}public static void main(String[] args) {Demo obj = new Demo("hdk1993", 21);obj.say();}}
3.使用this調用建構函式
在建構函式中,通過this可以調用同一class中別的建構函式,如
public class Flower {Flower(int petals) {}Flower(String ss) {}Flower(int petals, Sting ss) {// petals++;調用另一個建構函式的語句必須在最起始的位置this(petals);// this(ss);會產生錯誤,因為在一個建構函式中只能調用一個建構函式}}
值得注意的是:
(i):在構造調用另一個建構函式,調用動作必須置於最起始的位置。
(ii):不能在建構函式以外的任何函數內調用建構函式。
(iii):在一個建構函式內只能調用一個建構函式。
4.this作為函數傳回值
關於返回類自身的引用,Thing in Java有個很經典的例子,通過this 這個關鍵字返回自身這個對象然後在一條語句裡面實現多次的操作,還是貼出來。
public class ThisDemo {int number;ThisDemo increment() {number++;return this;}private void print() {System.out.println("number=" + number);}public static void main(String[] args) {ThisDemo tt = new ThisDemo();tt.increment().increment().increment().print();}}
5.this作為參數傳遞
需要在某些完全分離的類中調用一個方法,並將當前對象的一個引用作為參數傳遞時。例如:
public class Demo {public static void main(String[] args) {B b = new B(new A());}}class A {public A() {new B(this).print(); // 匿名對象}public void print() {System.out.println("Hello from A!");}}class B {A a;public B(A a) {this.a = a;}public void print() {a.print();System.out.println("Hello from B!");}}
運行結果:
Hello from A!
Hello from B!
在這個例子中,對象A的建構函式中,用new B(this)把對象A自己作為參數傳遞給了對象B的建構函式。
匿名對象就是沒有名字的對象。如果對象只使用一次,就可以作為匿名對象,代碼中 new B(this).print(); 等價於 ( new B(this) ).print();,先通過 new B(this) 建立一個沒有名字的對象,再調用它的方法。
6. 注意匿名類和內部類中的中的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();}}
在上面這個例子中, thread 是一個匿名類對象,在它的定義中,它的 run 函數裡用到了外部類的 run 函數。這時由於函數同名,直接調用就不行了。這時有兩種辦法,一種就是把外部的 run 函數換一個名字,但這種辦法對於一個開發到中途的應用來說是不可取的。那麼就可以用這個例子中的辦法用外部類的類名加上 this 引用來說明要調用的是外部類的方法 run。
Java之this詳解