標籤: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 的三種用法