java中的this關鍵字

來源:互聯網
上載者:User

標籤:

this:看上去,是用於區分局部變數和成員變數同名情況。

this,就是代表本類對象,到底是代表哪一個呢?

this代表它所在的函數所屬對象的引用。

簡單得說,哪個對象在調用this所在的函數,this就代表哪個對象。

Class Children{

  private String name;

  private int age;

  Children(String name){

    this.name=name;

  } 

  public boolean compare(Person p){

    return this.age==p.age;

  }

  public static void main(String[] str){

    Children c1=new Children (“Allen”);//this代表c1

    Children c2=new Children (“Rose”);//this代表c2

    c1.compare(c2);

  }

}

this的應用:當定義類中功能時,該函數內部都要用到調用該函數的對象時,這是用this來表示這個對象。

但凡本類功能內部使用了本類對象,都用this。

this關鍵字在建構函式間的調用:

Class Children{

  private String name;

  private int age;

  Children(String name){

    this.name=name;

  } 

  Children(String name,int age){

    this(name);

    this.age=age;

  }

}

this語句:用於建構函式之間進行相互調用。只能定義在建構函式的第一行,因為初始化要先執行。

java中的this關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.