更新時間:2021-09-01 來源:黑馬程序員 瀏覽量:
IT就到黑馬程序員.gif)
構(gòu)造方法的創(chuàng)建 :
如果沒有定義構(gòu)造方法,系統(tǒng)將給出一個默認(rèn)的無參數(shù)構(gòu)造方法,如果定義了構(gòu)造方法,系統(tǒng)將不再提供默認(rèn)的構(gòu)造方法。
構(gòu)造方法的重載 :
如果自定義了帶參構(gòu)造方法,還要使用無參數(shù)構(gòu)造方法,就必須再寫一個無參數(shù)構(gòu)造方法 :
推薦的使用方式
無論是否使用,都手工書寫無參數(shù)構(gòu)造方法
造方法.jpg)
重要功能 :
可以使用帶參構(gòu)造,為成員變量進(jìn)行初始化
示例代碼
/*
學(xué)生類
*/
class Student {
private String name;
private int age;
public Student() {}
public Student(String name) {
this.name = name;
}
public Student(int age) {
this.age = age;
}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println(name + "," + age);
}
}
/*
測試類
*/
public class StudentDemo {
public static void main(String[] args) {
//創(chuàng)建對象
Student s1 = new Student();
s1.show();
//public Student(String name)
Student s2 = new Student("林青霞");
s2.show();
//public Student(int age)
Student s3 = new Student(30);
s3.show();
//public Student(String name,int age)
Student s4 = new Student("林青霞",30);
s4.show();
}
}