一、如何初始化对象
在Java方法内部定义一个局部变量时,必须要初始化,否者会编译失败(如下)
public static void main(String[] args) {
int a;
System.out.println(a);
}
// Error:(26, 28) java: 可能尚未初始化变量a,改为int a=10;则可以
//如果是对象则:
public static void main(String[] args) {
Date d = new Date();
d.printDate();
d.setDate(2021,6,9); //调用类里面的setDate方法,较为麻烦
d.printDate();
}
二、构造器
构造方法
(
也称为构造器
)
是一个特殊的成员方法,
名字必须与类名相同,在创建对象时,由编译器自动调用,并且
在整个对象的生命周期内只调用一次。(
构造方法的作用就是对对象中的成员进行初始化,并不负责给对象开辟空间
)
格式: public 类名([参数]){
语句;
}
1、无(有)参构造器:
public class Date {
public int year;
public int month;
public int day;
// 无参构造方法
public Date(){
this.year = 1900;
this.month = 1;
this.day = 1;
}
// 带有三个参数的构造方法
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(year + "-" + month + "-" + day);
}
public static void main(String[] args) {
Date d = new Date();
d.printDate(); //调用无参的构造器,结果是1900-1-1
//Date d=new Date(1234,3,4);
//d.printDate(); 如果用这两行,调用的是有参构造器,则结果是1234-3-4
}
}
上述两个构造方法:名字相同,参数列表不同,因此构成了方法重载
当程序中既没有有参也没写无参构造器的时候,系统编译器默认会生成一个无参构造器,一旦写了构造器,编译器则不会在生成。
三、无参和有参构造器之间的关系
public class Date {
public int year;
public int month;
public int day;
public Date(){
//System.out.println(year); 注释取消掉,编译会失败(因为不在第一行)
this(1900, 1, 1); // 无参构造方法--内部给各个成员赋值初始值,该部分功能与三个参数的构造方法重复
// 此处可以在无参构造方法中通过this调用带有三个参数的构造方法
// 但是this(1900,1,1);必须是构造方法中第一条语句
//this.year = 1900;
//this.month = 1;
//this.day = 1;
}
// 带有三个参数的构造方法
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
}
无参的构造器可以调用三个参数的构造器,反过来三个参数的构造器则不能调用无参