public class Lesson {
String name;
int time;
public Lesson(String name,int time) {
// TODO Auto-generated constructor stub
this.name=name;
this.time=time;
}
static{
System.out.println("执行static代码块!");
}
{
System.out.println(this.name+",,"+this.time);
}
public void show(){
System.out.println(this.name+",,,"+this.time);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Lesson p = new Lesson("math", 48);
p.show();
}
}
运行结果为:
执行static代码块!null,,0
math,,,48
说明先执行static代码块,再执行构造代码块,然后执行构造函数。
Lesson p = new Lesson("math", 48);执行这句话的时候,计算机做的工作顺序为:
- 先将Lesson.class加载到内存当中;
- 执行该类的static代码块。如果有的话;
- 在堆内存中开辟空间,分配内存地址;
- 在堆内存中尽力对象的特有属性,并进行默认初始化;
- 对属性进行显示初始化;
- 对属性进行构造代码块初始化(也就是执行构造代码块中的内容);
- 对属性进行构造函数初始化;
- 将内存地址赋给栈内存中的p变量;