什么是构造方法
构造方法是一个特殊的成员方法,名字必须和类相同,在创建对象的时候,右边一起自动调用,并且在整个对象的生命周期内只调用一次.
public class Date {
public int year;
public int month;
public int day;
// 构造方法:
// 名字与类名相同,没有返回值类型,设置为void也不行
// 一般情况下使用public修饰
// 在创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次
public Date(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
System.out.println("Date(int,int,int)方法被调用了");
}
public void printDate(){
System.out.println(year + "-" + month + "-" + day);
}public static void main(String[] args) {
// 此处创建了一个Date类型的对象,并没有显式调用构造方法
Date d = new Date(2021,6,9); // 输出Date(int,int,int)方法被调用了
d.printDate(); // 2021-6-9
}
}
构造方法的特性
1.
名字必须与类名相同
2.
没有返回值类型,设置为
void
也不行
3.
创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次
(
相当于人的出生,每个人只能出生一次
)
4.
构造方法可以重载
(
用户根据自己的需求提供不同参数的构造方法
)
public class Date {
public int year;
public int month;
public int day;
// 无参构造方法
public Date(){
this.year = 1900;
this.month = 1;
this.day = 1;
}
上述两个构造方法:名字相同,参数列表不同,因此构成了方法重载。