java对象构造过程

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值