Java 静态语句块、语句块、构造函数执行顺序

本文详细解析了Java中父类和子类静态及非静态初始化块的执行顺序,并通过具体示例代码展示了整个执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单代码:

package example;

class Parent {
	static String name = "hello";

	{
		System.out.println("3 parent  block");
	}

	static {
		System.out.println("1 parent static block");
	}

	public Parent() {
		System.out.println("4 parent constructor");
	}
}

class Child extends Parent {
	static String childName = "hello";

	{
		System.out.println("5 child  block");
	}

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

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

package example;

public class StaticIniBlockOrderTest {
	public static void main(String[] args) {
		new Child();
	}
}

输出结果:

1 parent static block
2 child static block
3 parent  block
4 parent constructor
5 child  block
6 child constructor


执行顺序总结:

1、执行父类静态代码块,执行子类静态代码块

2、执行父类非静态代码块,执行父类构造函数,执行子类非静态代码块,执行子类构造函数



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值