隨筆 - 3, 文章 - 152, 評論 - 17, 引用 - 0
          數(shù)據(jù)加載中……

          談?wù)?Java 中 this 的使用

          1. this是指當前對象自己。
          當在一個類中要明確指出使用對象自己的的變量或函數(shù)時就應(yīng)該加上this引用。如下面這
          個例子中:

          public class A {

          String s = "Hello";

          public A(String s) {
          System.out.println("s = " + s);
          System.out.println("1 -> this.s = " + this.s);
          this.s = s;
          System.out.println("2 -> this.s = " + this.s);
          }

          public static void main(String[] args) {
          new A("HelloWorld!");
          }
          }

          運行結(jié)果:

          s = HelloWorld!
          1 -> this.s = Hello
          2 -> this.s = HelloWorld!

          在這個例子中,構(gòu)造函數(shù)A中,參數(shù)s與類A的變量s同名,這時如果直接對s進行操作則是對
          參數(shù)s進行操作。若要對類A的變量s進行操作就應(yīng)該用this進行引用。運行結(jié)果的第一行就
          是直接對參數(shù)s進行打印結(jié)果;后面兩行分別是對對象A的變量s進行操作前后的打印結(jié)果。


          2. 把this作為參數(shù)傳遞
          當你要把自己作為參數(shù)傳遞給別的對象時,也可以用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() {
          a.print();
          System.out.println("Hello from B!");
          }
          }

          運行結(jié)果:
          Hello from A!
          Hello from B!

          在這個例子中,對象A的構(gòu)造函數(shù)中,用new B(this)把對象A自己作為參數(shù)傳遞給了對象B
          的構(gòu)造函數(shù)。

          3. 注意匿名類和內(nèi)部類中的中的this。
          有時候,我們會用到一些內(nèi)部類和匿名類。當在匿名類中用this時,這個this則指的是匿
          名類或內(nèi)部類本身。這時如果我們要使用外部類的方法和變量的話,則應(yīng)該加上外部類的
          類名。如下面這個例子:

          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 函數(shù)里用到了
          外部類的 run 函數(shù)。這時由于函數(shù)同名,直接調(diào)用就不行了。這時有兩種辦法,一種就是
          把外部的 run 函數(shù)換一個名字,但這種辦法對于一個開發(fā)到中途的應(yīng)用來說是不可取的。
          那么就可以用這個例子中的辦法用外部類的類名加上 this 引用來說明要調(diào)用的是外部類
          的方法 run

          posted on 2005-03-05 18:16 閱讀(182) 評論(0)  編輯  收藏 所屬分類: J2se

          主站蜘蛛池模板: 邵东县| 横山县| 阿拉善盟| 顺义区| 榆林市| 黄骅市| 金阳县| 长宁区| 栾城县| 梁河县| 遂宁市| 伊川县| 翁牛特旗| 重庆市| 阿坝| 东宁县| 沾益县| 通化市| 潼关县| 会泽县| 宝兴县| 尼木县| 山阳县| 壤塘县| 榕江县| 隆回县| 井冈山市| 海安县| 克东县| 吴忠市| 且末县| 偃师市| 和静县| 鄢陵县| 刚察县| 普兰店市| 浑源县| 曲松县| 安远县| 蒙自县| 文水县|