構造方法的定義
構造方法也叫構造器或者構造函數
構造方法與類名相同,沒有返回值,連void都不能寫
構造方法可以重載(重載:方法名稱相同,參數列表不同)
如果一個類中沒有構造方法,那么編譯器會為類加上一個默認的構造方法。
默認構造方法格式如下:
public 類名() {
}
如果手動添加了構造器,那么默認構造器就會消失。
建議代碼中將無參構造器寫出來。
public class Student { public String name; public int age; public void eat() { System.out.println("eat...."); } //構造器 /** * 名稱與類名相同,沒有返回值,不能寫void * 構造器可以重載 * 如果類中沒有手動添加構造器,編譯器會默認再添加一個無參構造器 * 如果手動添加了構造器(無論什么形式),默認構造器就會消失 */ public Student() { System.out.println("無參構造器"); } public Student(int a) { System.out.println("一個參數的構造器"); age = 15; } public Student(int a, String s) { System.out.println("兩個參數的構造器"); age = a; name = s; } }
構造方法的作用
構造方法在創建對象時調用,具體調用哪一個由參數決定。
構造方法的作用是為正在創建的對象的成員變量賦初值。
public class Test { public static void main(String[] args) { //調用無參構造器 Student s1 = new Student(); //調用有參構造器 Student s2 = new Student(15); System.out.println(s2.age); Student s3 = new Student(34, "小明"); System.out.println(s3.name + ":" + s3.age); } }
構造方法種this的使用
構造方法種可以使用this,表示剛剛創建的對象
構造方法種this可用於
this訪問對象屬性
this訪問實例方法
this在構造方法中調用重載的其他構造方法(要避免陷入死循環)
只能位於第一行
不會觸發新對象的創建
public class Student { public String name; public int age; public void eat() { System.out.println("eat...."); } //構造器 //使用this()調用重載構造器不能同時相互調用,避免陷入死循環 public Student() { //this()必須出現在構造器的第一行,不會創建新的對象 this(15);//調用了具有int類型參數的構造器 System.out.println("默認構造器"); } public Student(int a) { this.eat(); eat();//this.可以省略 } //this在構造器中表示剛剛創建的對象 public Student(int a, String s) { System.out.println("兩個參數的構造器"); this.age = a; this.name = s; } }
public class Test { public static void main(String[] args) { Student s1 = new Student(15, "小明"); System.out.println(s1.name + ":" + s1.age); Student s2 = new Student(12, "小紅"); System.out.println(s2.name + ":" + s2.age); Student s3 = new Student(); } }
歸納this在實例方法和構造方法種的作用
this是java多態的體現之一
this只可以在構造方法和實例方法種存在,不能出現在static修飾的方法或代碼塊中
this在構造方法中表示剛剛創建的對象
this在實例方法種表示調用改方法的對象
this可以在實例方法和構造方法中訪問對象屬性和實例方法
this有時可以省略
this可以在實例方法中作為返回值
this可以當作實參
this可調用重載的構造方法