简单介绍一下对象的初始化顺序,
- 类加载之后,从父类到子类(自上而下)执行static修饰的语句(静态块)
- 当static语句执行完之后,再执行main()方法。
- 如果有对象new了自身对象,将自上到下执行构造代码块、构造器。
静态块>主方法>构造块>构造方法
注:
构造代码块:直接在类中定义切没有加static关键字的代码块,每次创建对象都会被调用,并且执行次序优先于类构造器。
public class Father {
static {
System.out.println("static a ");
}
{
System.out.println("aa");
}
public Father(){
System.out.println("father");
}
}
public class Child extends Father{
public Child(){
System.out.println("child");
}
static {
System.out.println("static b ");
}
{
System.out.println("bb");
}
public static void main(String[] args) {
Father f = new Child();
Father f1 = new Father();
}
}
static a
static b
aa
bb
father
child
aa
father