静态代码块、构造代码块、构造函数的执行顺序(Java)

首先来看看静态构造代码块长啥样子:

static{
	...
}

而普通的构造代码块相较之下只是少了一个static关键字

{
	...
}

在类的执行过程中,代码块和构造函数、main方法的执行顺序有事什么样的呢?请看如下:
以下示例中包含静态代码块、构造代码块、构造函数。创建了两个对象。

package codeblock;
/**
 * 静态方法块只会在最初的时候调用一次
 * 但是普通构造方法块在每个对象产生的地方都会调用一次
 * 执行顺序:静态代码块 --> main方法 --> 普通构造代码块 --> 构造函数
 * @author bamboo
 *
 */
public class Block {
	
	private static String name = null;
	private static int age = 0;
	private static String way = null;
	
	public Block(){
		System.out.println("this is father's constructor method");
	}

	static {
		age = 18;
		name = "张三";
		way = "父亲静态方法块";
		System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
	}
	
	{
		age = 30;
		name = "李四";
		way = "父亲普通方法块";
		System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
	}
	
	public static void main(String[] args) {
		System.out.println("this is father's main method");
		System.out.println();
		
		Block block1 = new Block();
		System.out.println();
		
		Block block2 = new Block();
	}
}

输出结果如下:
因为接下来这个类会作为父类,所以在输出里面信息说明清楚。
可以看出执行顺序如下:
静态代码块 --> main方法 --> 普通构造代码块 --> 构造函数。
值得注意的是静态代码块只会在最初的时候调用一次,而构造代码块在每次产生对象的时候都会调用。

名字 : 张三 年龄:18 构造: 父亲静态方法块
this is father's main method

名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method

名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method

子类(SunBlock)继承父类(Block),查看调用顺序。
子类如下:

package codeblock;

public class SunBlock extends Block{
	
	private static String name = null;
	private static int age = 0;
	private static String way = null;
	
	public SunBlock() {
		System.out.println("this is sun's constructor method");
	}
	
	static {
		age = 1;
		name = "小张三";
		way = "儿子静态方法块";
		System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
	}
	
	{
		age = 3;
		name = "小李四";
		way = "儿子普通方法块";
		System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
	}
	
	public static void main(String[] args) {
		System.out.println("this is sun's main method");
		System.out.println();
		
		SunBlock sun1 = new SunBlock();
		System.out.println();
		
		SunBlock sun2 = new SunBlock();
	}

}

执行结果:

名字 : 张三 年龄:18 构造: 父亲静态方法块
名字 : 小张三 年龄:1 构造: 儿子静态方法块
this is sun's main method

名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method
名字 : 小李四 年龄:3 构造: 儿子普通方法块
this is sun's constructor method

名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method
名字 : 小李四 年龄:3 构造: 儿子普通方法块
this is sun's constructor method

可以看出执行顺序如下:
父类的静态代码块 --> 子类的静态代码块 -->main函数 --> 父类构造代码块 --> 父类构造函数 --> 子类构造代码块 --> 子类构造函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值