假如在一段代码中,对同一个对象初始化时有多次赋值语句,那么赋值的先后顺序应该是怎样的呢?这就涉及到了对象的初始化过程。
对象的初始化过程分为四步:
1.给对象的实例变量(非“常量”)分配内存空间,默认初始化成员变量;
2.成员变量声明时的初始化;
3.初始化块初始化(又称为构造代码块或非静态代码块);
4.构造方法初始化
我们用一个例子详述这四个过程:
package mcing;
public class Student {
String stuName="";
int stuAge=-1;
int stuSex=-1;
int stuGrade=-1;
{
System.out.println("使用初始化块初始化");
this.stuName="雷静";
this.stuAge=22;
this.stuSex=2;
this.stuGrade=4;
}
public Student() {
System.out.println("使用无参构造方法初始化");
}
public Student(String stuName, int stuAge, int stuSex, int stuGrade) {
System.out.println("使用有参构造方法初始化");
this.stuName = stuName;
this.stuAge = stuAge;
this.stuSex = stuSex;
this.stuGrade = stuGrade;
}
public static void main(String[] args) {
Student temp = new Student("王云",22,1,4);
System.out.println(temp.stuName+" "+temp.stuAge+" "+temp.stuSex+" "+temp.stuGrade);
}
}
在这段代码中,新创建的对象student的成员变量先被初始化为默认值,如下:
然后进行下一步,执行成员变量声明时的初始化:
然后进行第三步,执行初始化块中的初始化:
最后再执行构造方法中的初始化:
以上四幅图还解释了对象的存储方式:在堆中开辟一段空间存储对象中的数据,然后在栈中开辟一段空间存储堆中这段空间的地址,也就是说如果打印temp,输出的会是一个地址。
以下是刚才那段代码的运行结果: