JAVA中this關鍵字的用法

 

this關鍵字主要有三個應用:html

1.調用本類中的屬性,也就是類的成員變量;java

2.調用本類中的其餘方法;函數

3.調用本類中的其餘構造方法,調用時候要放在構造方法的首行。this

* this關鍵詞除了能夠調用變量或者成員方法以外,最引人注目的是它能夠返回類的引用。如在本類中使用return this ,便可返回對類的引用。如代碼在student類上,那麼return this 即表明着return student。spa

*------------------------------------------------------------------------------------------------------------------------------------分割線——————————————————————————————————————————————————————————*htm

java中構造方法的特性:對象

  • 當前類的其餘構造方法經過this語句調用;
  • 當前類的子類的構造方法經過super語句調用;
  • 在程序中經過new語句調用。

 

 *------------------------------------------------------------------------------------------------------------------------------------分割線——————————————————————————————————————————————————————————*blog

參考文檔 :http://www.cnblogs.com/nolonely/p/5916602.html事件

1.當成員變量和局部變量重名的時候,在方法中使用this則表明的是類的成員變量。文檔

2.把本身看成參數傳遞時,也能夠用this.(this做當前參數進行傳遞)

3.有時候,咱們會用到一些內部類和匿名類,如事件處理。當在匿名類中用this時,這個this則指的是匿名類或內部類自己。這時若是咱們要使用外部類的方法和變量的話,則應該加上外部類的類名。如:

public class HelloB {
    int i = 1;
 
    public HelloB() {
       Thread thread = new Thread() {
           public void run() {
              for (int j=0;j<20;j++) {
                  HelloB.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 HelloB();
    }
}

4.在構造函數中,經過this能夠調用同一類中別的構造函數。如:

public class Test{
  private static String b = "dsd";
  
  public Test(){
    this(b);
    
  }
  
  public Test(String a){
    System.out.println(a);
  }
  
}

5.this同時傳遞多個參數

public class TestClass {
    int x;
    int y;
 
    static void showtest(TestClass tc) {//實例化對象
       System.out.println(tc.x + " " + tc.y);
    }
    void seeit() {
       showtest(this);
    }
 
    public static void main(String[] args) {
       TestClass p = new TestClass();
       p.x = 9;
       p.y = 10;
       p.seeit();
    }
}
相關文章
相關標籤/搜索