父子类都有代码块,静态代码块,构造方法。创建子类,代码执行的顺序。
class Father {
{
System.out.println("I am father's code block");
}
static {
System.out.println("I am father's static code block");
}
public Father(){
System.out.println("I am father's constructor");
}
}
class Son extends Father {
{
System.out.println("I am son's code block");
}
static {
System.out.println("I am son's static code block");
}
public Son(){
System.out.println("I am son's constructor");
}
}
public class Test{
public static void main(String[] args){
new Son();
}
}
控制台输出如下:
I am father's static code block
I am son's static code block
I am father's code block
I am father's constructor
I am son's code block
I am son's constructor
由此可知,代码执行顺序如下:
- 父类静态代码块
- 子类静态代码块
- 父类代码块
- 父类构造方法
- 子类代码块
- 子类构造方法