java对象实例化过程中的代码执行顺序

时间:2023-02-24 22:34:44

java对象实例化过程中的代码执行顺序

1、执行顺序

(1)执行父类静态的内容,父类静态的内容执行完毕后,接着去执行子类的静态的内容;
(2)子类的静态内容执行完毕之后,初始化父类的成员变量--->执行父类的非静态语
句块--->执行父类的构造方法。
(3)父类的构造方法执行完毕之后,初始化子类的成员变量--->执行子类的非静态语
句块--->执行子类的构造方法。

2、例证

(1)Base.java

public class Base{

public String whenAmISet = "set when declared in parent class";

Base() {
System.out.println("4 parent Constructor , it will invoke
preProcess() from child class."
);
preProcess(); //调用子类的preProcess;
}

void preProcess() {}
//静态语句块
static {
System.out.println("1 parent static block ");
}
//非静态语句块
{
System.out.println("3 parent dynamic block , after
initialized filed from parent class,"
);
}
}

(2)Derived.java

public class Derived extends Base
{

public String whenAmISet = "set when declared";

@Override void preProcess()
{
whenAmISet = "set in preProcess()";
}

Derived() {
System.out.println("6 child constructor ");
}

static {

System.out.println("2 child static block");
}

{
System.out.println("5 child dynamic block , after
initialized filed from child class."
);
}
}

(3)Main.java

public class Main
{

public static void main(String[] args)
{
Derived d = new Derived();
System.out.println( d.whenAmISet );
}
}

输出:
1 parent static block
2 child static block
3 parent dynamic block , after initialized filed from parent class,
4 parent Constructor , it will invoke preProcess() from child class.
5 child dynamic block , after initialized filed from child class.
6 child constructor
set when declared

提示:想观察执行顺序,可在eclipse选用debug模式,在每行代码输出处打断点观察执行顺序。

参考资料:
(1)Java 静态语句块、语句块、构造函数执行顺序
http://www.cnblogs.com/jycboy/p/5257615.html