2020.7.15
阿新 • • 發佈:2020-07-16
一、今日學習內容
1、類的屬性
(1)屬性:成員屬性(全域性變數),區域性變數
成員屬性:定義在類中,而在方法外,他的範圍歸整個類所共享。
1 public class Person{ 2 private String name; 3 private int age; 4 public static void main(String[] args){ 5 Person p=new Person(); 6 System.out.println(p.name+","+p.age); 7 } 8 }
輸出結果:null,0
通常使用者不會直接去訪問或修改屬性,因為這樣的訪問和修改是及其危險的,所以通常會對屬性進行封裝,使用getXXX得到屬性值,使用setXXX設定屬性值。
例:
區域性變數:定義在方法內部,作用範圍到方法尾結束。
1 public class JuBuDemo{ 2 public static void main(String[] args){ 3 } 4 public void t(){ 5 int x=7;//區域性變數 6 System.out.println("x="+x); 7 } 8 }
(2)this關鍵字:this指的是當前物件
1 public class ThisDemo{ 2 int x=5; 3 public void ThisDemo(int x){ 4 this.x=x;//this.x指的是屬性x;方法傳入的x,指的是形參x 5 } 6 public static void main(String[] args){ 7 ThisDemo demo=new ThisDemo(9); 8 Systemout.println(demo.x); 9 } 10 }
輸出結果:9
例項: 呼叫方法
1 public class ThisDemo{ 2 public static void main(String[] args){ 3 } 4 public void t(){ 5 System.out.println("t"); 6 } 7 public void t2(){ 8 this.t(); 9 } 10 }
例項:呼叫無參構造方法
1 public class ThisDemo{ 2 int x; 3 public ThisDemo(){ 4 System.out.println("無參建構函式“); 5 } 6 public ThisDemo(int x){ 7 this(); 8 this.x=x; 9 } 10 }
this()指的是呼叫本類中的無參構造器。
例項:呼叫有參構造方法
1 public class ThisDemo{ 2 int x; 3 public ThisDemo(){ 4 System.out.println("無參建構函式“); 5 } 6 public ThisDemo(int x){ 7 this(); 8 this.x=x; 9 } 10 public ThisDemo(int x,int y){ 11 this(x); 12 y=20; 13 } 14 }
this(x)指的是呼叫本類中的有參構造器。
注:使用this指標時,this關鍵字必須放在構造器的第一行,否則會報錯。
二、遇到的問題
今天沒有遇到什麼太大的問題
三、明日計劃
繼續學習第四章的內容