国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

淺談 Java 中 this 的使用

2019-11-18 13:13:09
字體:
來源:轉載
供稿:網友

  1. this是指當前對象自己
  當在一個類中要明確指出使用對象自己的的變量或函數時就應該加上this引用。如下面這個例子中:
  
  public class A {
  
  String s = "Hello";
  
  public A(String s) {
  System.out. this.s = " + this.s);
  this.s = s;
  System.out.println("2 -> this.s = " + this.s);
  }
  
  public static void main(String[] args) {
  new A("HelloWorld!");
  }
  }
  
  運行結果:
  
  s = HelloWorld!
  1 -> this.s = Hello
  2 -> this.s = HelloWorld!
  
  在這個例子中,構造函數A中,參數s與類A的變量s同名,這時假如直接對s進行操作則是對參數s進行操作。若要對類A的變量s進行操作就應該用this進行引用。運行結果的第一行就是直接對參數s進行打印結果;后面兩行分別是對對象A的變量s進行操作前后的打印結果。
  
  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() {
  a.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();
  }
  
  }
  
  在上面這個例子中, thread 是一個匿名類對象,在它的定義中,它的 run 函數里用到了外部類的 run 函數。這時由于函數同名,直接調用就不行了。這時有兩種辦法,一種就是把外部的 run 函數換一個名字,但這種辦法對于一個開發到中途的應用來說是不可取的。那么就可以用這個例子中的辦法用外部類的類名加上 this 引用來說明要調用的是外部類的方法 run。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 汤原县| 太康县| 乌鲁木齐县| 屯昌县| 赤水市| 贵阳市| 锡林郭勒盟| 盐池县| 湖北省| 宣武区| 柳州市| 巍山| 开鲁县| 黎城县| 大余县| 社旗县| 武穴市| 新昌县| 长宁区| 宝清县| 玉林市| 特克斯县| 松原市| 焉耆| 福海县| 泸水县| 那曲县| 临泽县| 台中市| 库车县| 财经| 新营市| 宕昌县| 南昌市| 龙胜| 从化市| 谢通门县| 敦化市| 银川市| 集贤县| 舒城县|