構(gòu)造函數(shù)
什么是構(gòu)造方法
構(gòu)造方法也叫構(gòu)造函數(shù),或者叫構(gòu)造器
- 構(gòu)造方法的方法名必須與類名相同
- 構(gòu)造方法沒有返回值,也不寫void
class Student {
//構(gòu)造方法
Student(){
}
}
注意:下面這個方法是構(gòu)造方法嗎
class Student {
void Student(){//普通方法,可有對象調(diào)用
}
void play(){
}
}
答:不是
第2行的Student()方法前面添加了void,因此不是構(gòu)造方法,此時它是一個普通的方法。與play方法一樣??梢允褂脤嵗髮ο笳{(diào)用Student()方法。
不推薦把普通方法名稱定義為與類名相同。
構(gòu)造方法的作用
類的屬性在實例化時被賦予默認值。那么是誰給雷達屬性賦的默認值呢???????
class Student {
String name;
int score;
String no;
public static void main(String[] args) {
Student s1 = new Student();//實例化,此時name,score,no都有默認值了。
}
}
對象的屬性的默認值是由構(gòu)造方法賦值的。
構(gòu)造方法的作用:為對象的屬性初始化。
默認構(gòu)造函數(shù)
一個類如果沒有顯示的定義構(gòu)造函數(shù),那么這個類默認具有無參的構(gòu)造函數(shù)。
默認構(gòu)造函數(shù)為對象的屬性賦默認值。
代碼示例
class Student {
String name;
int score;
String no;
public void play(){
System.out.printf("我的名字是%s,我的成績是%d,我的學號是%s",this.name,this.score,this.no);
}
}
public class StudentTest {
public static void main(String[] args) {
Student s1 =new Student();
s1.play();
}
}
輸出結(jié)果是:
我的名字是null,我的成績是0,我的學號是null
為什么輸出的是null,0null?
因為本例中沒有定義構(gòu)造函數(shù),系統(tǒng)會自動添加一個默認構(gòu)造函數(shù),默認構(gòu)造函數(shù)是無參的,會為所有的屬性賦默認值,因此name是null,score是0,no是null。
特殊情況:
如果顯示的定義了構(gòu)造函數(shù),那么默認構(gòu)造函數(shù)就消失不存在了。
例如:
class Student {
String name;
int score;
String no;
//顯示定義構(gòu)造函數(shù),此時默認構(gòu)造函數(shù)就沒有了
Student(){
}
}
構(gòu)造方法的調(diào)用
構(gòu)造方法是在實例化對象時調(diào)用的。并且實例化時傳遞的參數(shù)必須有構(gòu)造方法的參數(shù)一致。
例如
class Student {
String name;
int score;
String no;
/**
* 有兩個參數(shù)的構(gòu)造方法
* @param name1
* @param score1
*/
Student(String name1,int score1){
name= name1;
score= score1;
}
}
public class StudentTest {
public static void main(String[] args) {
Student s1 =new Student("haha",76);//調(diào)用student類的構(gòu)造方法,為name和score屬性初始化,no為默認值null
}
}
構(gòu)造方法不允許通過對象名調(diào)用。例如下面的調(diào)用是錯誤的
public static void main(String[] args) {
Student s1 =new Student("haha",76);
s1.Student("haha",88);//錯誤的,對象名不允許調(diào)用構(gòu)造函數(shù)
}