java關鍵字this

來源:互聯網
上載者:User

標籤:

關鍵字this是指向調用對象本身的引用名;

   

每當一個對象建立後,Java虛擬機器會給這個對象分配一個引用自身的指標,這個指標的名字就是 this;

   

   

《java編程思想》中關於this的筆記:

this關鍵字只能在方法內部使用,表示對"調用方法的那個對象"的引用;

在方法內部調用同一個類的另一個方法,就不必使用this,直接調用即可,當然你也可以加上;

我們沒有必要加上this,因為編譯器能幫我們自動添加;

舉例:如下方法在testThisOne加上this和沒有加是一樣的;

源碼:

public class thisTest{

public static void main(String[] args){

Test test = new Test();

test.testThisOne();

}

}

   

class Test{

public void testThisOne(){

testThisTwo(10);

this.testThisTwo(100);

}

   

public void testThisTwo(int i){

System.out.println(i);

}

}

運行結果:

   

可以使用return this返回這個對象的引用;

   

他人部落格總結

這個部落格中說道:this只能在類中的非靜態方法中靜態方法和靜態代碼塊中絕對不能出現this;this只能和特定的對象關聯,而不和類關聯,同一個類的不同對象有不同的this;

嘗試:試著在static方法中使用this,如結果所示,如果在testThisOne中使用this,則會報以下變異錯誤,如果不使用this,運行正常;

源碼:

public class thisTest{

public static void main(String[] args){

Test test = new Test();

test.testThisOne();

}

}

   

class Test{

public static void testThisOne(){

this.testThisTwo(100);

}

   

public static void testThisTwo(int i){

System.out.println(i);

}

}

運行結果:

   

   

   

this用法

用法一:引用類的隱藏資料域(hidden data);函數參數或者函數中的局部變數和成員變數同名的情況下,成員變數被屏蔽;

   

舉例:通過輸出this.i,可以看出,this的作用是調用該對象的變數i,因為是類裡面的成員變數,基礎資料型別 (Elementary Data Type)沒有初始化的時候會自動初始化,int預設為0;在Myprint方法中有變數i,但這裡由於this指向的是對象本身的引用名,所以這裡this.i是類的成員變數i,而不是方法中定義的i;

源碼:

public class thisTest{

public static void main(String[] args){

Test test = new Test();

test.Myprint(10);

}

}

   

class Test{

private static int i;

public void Myprint(int i){

System.out.println(i);

System.out.println(this.i);

}

}

運行結果:

   

用法二:讓構造方法調用同一個類的另一個構造方法;

舉例:如下所示,new Test()調用的是無參建構函式,但是在無參建構函式中用this(參數列表)的方式調用了另一個有參建構函式

源碼:

public class thisTest{

public static void main(String[] args){

Test test = new Test();

}

}

   

class Test{

public Test(){

this(10);

}

   

public Test(int i){

System.out.println(i);

}

}

   

運行結果:

   

   

   

總結:

關於this的用法大概就這麼些,其它的例如為什麼static中不能使用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.