構造方法的定義java
構造方法也叫構造器或者構造函數函數
構造方法與類名相同,沒有返回值,連void都不能寫this
構造方法能夠重載(重載:方法名稱相同,參數列表不一樣)spa
若是一個類中沒有構造方法,那麼編譯器會爲類加上一個默認的構造方法。code
默認構造方法格式以下:對象
public 類名() {blog
}編譯器
若是手動添加了構造器,那麼默認構造器就會消失。編譯
建議代碼中將無參構造器寫出來。class
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可調用重載的構造方法