Java代码块执行顺序

先定义一个输出类

public class Output {

	private String out;
	
	public Output(String out){
		System.out.println(out);
	}
}

父类

public class CodeBlockExecutedParent {
	private static Output out1=new Output("parent's static property");
	private Output out3=new Output("parent's property");
	static{
		out1=new Output("parent's static block");
	}
	{
		out1=new Output("parent's block");
	}
	public CodeBlockExecutedParent(){
		out1=new Output("parent's constructor");
	}
}


子类

public class CodeBlockExecuted extends CodeBlockExecutedParent {
	private static Output out=new Output("clilden's static property");
	private Output out2=new Output("childre's property");
	static{
		out=new Output("children's static block");
	}
	public CodeBlockExecuted(){
		out=new Output("childern's constructor");
	}
	{
		out=new Output("childen's block");
	}
	public static void main(String[] args){
		CodeBlockExecuted code=new CodeBlockExecuted();
	}
}



输出结果

parent's static property
parent's static block
clilden's static property
children's static block
parent's property
parent's block
parent's constructor
childre's property
childen's block
childern's constructor


由此可以看出执行顺序:父类静态属性-》父类静态代码块-》子类静态变量-》子类静态代码块-》父类非静态变量-》父类非静态代码块-》父类构造函数-》子类非静态变量-》子类非静态代码块-》-》子类构造函数(注--在父类或子类中属性和代码块的执行顺序不定决定于申明顺序)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值