总结对象的创建过程

首先看一个例子,以这个例子引导。

public class Test {
	public A(int id) {
		System.out.println("Test(" + id + ")");
	}
}
class Demo {
	//静态块
	static {
		System.out.println("This is static block!");
	}
	//非静态块
	{
		System.out.println("This is non-static block!");
	}
	
	Test t1 = new Test(1); //------------------1--------------------
	
	public Demo() {
		System.out.println("This is Demo's constructor!");
		Test t2 = new Test(2);
	}
	
	Test t3 = new Test(3);
	
	public static void main(String[] args) {
		Demo dm = new Demo();
	}
}

输出:

This is static block!

This is non-static block!

Test(1)

Test(3)

This is Demo's constructor!

Test(2)

由此看出:

1、先装载.class文件,创建Class对象,对静态数据(由static声明的)进行初始化,而且只进行一次初始化。

2、new Demo()在堆上进行空间分配。

3、执行非静态块。

4、执行所有方法外定义的变量初始化。

5、执行构造方法。

在上例中,若在注释1行前面加上static关键字,输出就为变为:

This is static block!

Test(1)

This is non-static block!

Test(3)

This is Demo's constructor!

Test(2)

由此看出静态数据时在装载的时候执行的,且只执行一次。总体来说,执行顺序为:静态块,静态属性(装载时)->非静态块,属性->构造方法。

指出:对于静态块和静态属性或非静态块和静态属性的执行顺序决定于它们在代码中的顺序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值