java对象构造过程

来源:互联网 发布:java jsonrpc 框架 编辑:程序博客网 时间:2024/05/21 08:57

Java对象构造过程

例如有个Child 类继承了Father类,当new Child()调用后执行过程如下

1. 类加载器加载Child类发现其有父类Father类,先加载Father类

2. 执行Father类的静态block初始化段以及静态成员变量初始化,顺序按照其在Class内申明的顺序

3. 加载Child类,执行Child类的静态block初始化段以及静态成员变量初始化,顺序按照其在Class内申明的顺序

4. 初始化Father对象,执行Father对象的成员变量初始化以及block初始化段,顺序按照其在Class内申明的顺序

5. 执行Father对象的构造函数

5. 初始化Child对象,执行Child对象的成员变量初始化以及block初始化段,顺序按照其在Class内申明的顺序

6. 执行Child对象的构造函数


代码段如下,github地址 https://github.com/hzllblzjily/entityconstruction

/** *  */package com.hongbao.entitycontruction;/** * @author hzllb * * 2016年1月15日 */public class Father {static TestOutput testOutput = new TestOutput("Father static entity object");TestOutput testOutput2 = new TestOutput("Father object entity object");static{System.out.println("Father static block");}{System.out.println("Father object block");}public Father(){System.out.println("Father construction");}}/** *  */package com.hongbao.entitycontruction;/** * @author hzllb * * 2016年1月15日 */public class Child extends Father{static TestOutput testOutput = new TestOutput("Child static entity object");TestOutput testOutput2 = new TestOutput("Child object entity object");static{System.out.println("Child static block");}{System.out.println("Child object block");}public Child(){super();System.out.println("Child construction");}}/** *  */package com.hongbao.entitycontruction;/** * @author hzllb * * 2016年1月15日 */public class TestOutput {public TestOutput(String str){System.out.println(str);}}package com.hongbao.entitycontruction;/** * Hello world! * */public class App {    public static void main( String[] args )    {        Child child = new Child();    }}

最后的输出为

Father static entity object

Father static block

Child static entity object

Child static block

Father object entity object

Father object block

Father construction

Child object entity object

Child object block

Child construction


0 0