java中 this 的三種用法

來源:互聯網
上載者:User

標籤:new   string   font   code   ring   size   str   變數   成員方法   

Java中this的三種用法

調用屬性

(1)this可以調用本類中的任何成員變數

調用方法(可省略)

(2)this調用本類中的成員方法(在main方法裡面沒有辦法通過this調用)

調用構造方法

(3)this調用構造方法只能在本構造方法中調用另一個構造方法
(4)this 調用構造方法必須寫在第一行

eg:

 1 public class ThisDemo { 2     private int id; 3     private String name; 4     public ThisDemo(){   //(1)this可以調用本類中的任何成員變數 5         name="CosmosRay"; 6         id=110; 7         //this.shoInfo();==shoInfo(); 8         this.shoInfo(); //(2)this調用本類中的成員方法(在main方法裡面沒有辦法通過this調用) 9     }10     public ThisDemo(String name){  11         this.name=name;12     }13     public ThisDemo(String name,int id){14 //        this();         //this調用本類中的無參構造方法15         //(3)this調用構造方法只能在本構造方法中調用另一個構造方法16         //(4)this 調用構造方法必須寫在第一行17         this(name);         //this調用本類中的有參構造方法18     }19     public void shoInfo(){20         System.out.println(this.id+" "+this.name);21     }22     public static void main(String[] args){   //程式的入口,static23         new ThisDemo("李四");  //匿名對象24         ThisDemo demo;  //定義一個變數名25         demo=new ThisDemo();  //建立一個對象26         27     }28 }

 

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.