先定义一个输出类
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
由此可以看出执行顺序:父类静态属性-》父类静态代码块-》子类静态变量-》子类静态代码块-》父类非静态变量-》父类非静态代码块-》父类构造函数-》子类非静态变量-》子类非静态代码块-》-》子类构造函数(注--在父类或子类中属性和代码块的执行顺序不定决定于申明顺序)