Java中this關鍵字的用法

在類的方法定義中使用的this關鍵字代表使用該方法的對象的引用,this指向的是自身對象的引用,我們可以通過一個小例子分析一下內存分配情況:

代碼展示:

public  class  Leaf{
   int i = 0;
   Leaf ( int i ){ this.i=i; }
   Leaf increament(){
      i++;
      return this;
   }
   void print() { 
      System.out.println(“i = ” + I );
   }
   Public static void main(String [] args){
      Leaf leaf = new (100);
      leaf.increament().increament().print(); 
   }
}

內存分析:

首先,棧空間中有個leaf,它指向我們新new出來的Leaf,其Leaf分配在堆空間中;

其次,調用Leaf的構造方法,在棧空間裏分配構造方法的形參i,其值爲100;在Leaf中有成員變量i,然後把棧裏形參i的值賦給堆空間Leaf成員變量i(爲100),構造方法完成,棧中的形參i消失;


再次,執行leaf.increament().increament()第一個ncreament(),其i++,則i變爲101;return在我們棧空間分配一個臨時的內存,這塊內容是this的內容,this指向其對象自身,則在棧空間分配的這個臨時空間也指向該對象;


然後,執行leaf.increament().increament()第二個ncreament(),其是對佔內存分配的臨時空間調用,即相當於對自身對象繼續調用,此時i爲102;接着return  this,則又重複上面的過程我就不在重複解說,圖示說明;


最後,調用print()方法,打印輸出結果:


下面我們就介紹一下,this的幾種用法:

(1)      當成員變量和構造方法中的參數重名時,在方法中使用this表明類中的成員變量。

代碼如下:

public  class  Leaf{
   int i = 0;
   Leaf ( int i){ 
     this.i = i; 
   }
}

(1)      把自己當參數傳遞

代碼如下:

class  Fruit{
   Fruit(){
      New Apple(this).print; //調用B的方法
   }
   void print(){
       System.out.println(“歡迎來到水果世界”);
   }
}

class Apple{
Fruit fruit;
Apple ( Fruit fruit){
   this.fruit = fruit;
}
void print(){
   a.print();//調用Fruit的方法
   b.System.out.println(“歡迎來到蘋果世界”);
} 
} 

在這裏,對象Fruit的構造函數中,用new Apple(this)把對象Fruit自己當做參數傳遞給了對象Apple的構造函數。

3、在構造函數中,通常this可以調用同一類中別的構造函數。

代碼如下:

Public class Person{
   String name;
   int age;
   String sex;
   Person (string n, int g , string s){
      name = n;
      age = g;
      sex = s;
   }
   Person ( string n ,I nt g){
      This(n,g,”男”)
   }

4、this同時傳遞多個參數。

Public class Person{
   String name;
   int age;
  static  void  show( Person person){
    System.out.println( person.name + “,” + person.age);
   } 
  void  see(){
     show(this);
  }
   }

 這裏相當於吧當前實例化的person傳給了show()方法。

5、當用到一些內部類或匿名類,如事件處理。在匿名類中用this時,這個this指的是匿名類或內部類本身。這時如果我們要使用外部類的方法和變量的話,則應該加上外部類的類名。

Public class Person{
   Person ( ) {
      Thread  thread  = new Thread ( ){
         Void run ( ){
             Person.this.run();//調用外部類的方法
          }
      }
    void  run ( ){
       System.out.println(“跑”);
     }
   }

在這裏,thread 是一個匿名類對象,在它的定義中,它的 run 函數裏用到了外部類的 run 函數。這時由於函數同名,直接調用就不行了。這時有兩種辦法,一種就是把外部的 run 函數換一個名字,但這種辦法對於一個開發到中途的應用來說是不可取的。那麼就可以用這個例子中的辦法用外部類的類名加上 this 引用來說明要調用的是外部類的方法 run。

總之,this不管有幾種用法,它都是代表使用該方法的對象的引用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章