目录
JVM代码:
public class JVM {
JVM(){
System.out.println(" JVM的无参构造函数 "+count);
}
// 静态变量
public static int count;
{
System.out.println(" JVM的构造代码块 "+count);
}
static {
System.out.println(" JVM的静态代码块 "+count);
}
}JVMParent代码:
public class JVMParent extends JVM{
JVMParent(){
System.out.println(" JVMParent的无参构造函数 "+count);
}
// 静态变量
public static int count;
{
System.out.println(" JVMParent的构造代码块 "+count);
}
static {
System.out.println(" JVMParent的静态代码块 "+count);
}
JVMParent(String str){
System.out.println(" JVMParent的有参构造函数 "+str+" "+count);
}
}JVMSons代码:
public class JVMSons extends JVMParent{
public static void main(String[] args) {
System.out.println("main");
new JVMSons();
}
static {
System.out.println(" JVMSons的静态代码块 ");
}
JVMSons(){
System.out.println(" JVMSons的无参构造函数 ");
}
JVMSons(String str){
System.out.println(" JVMSons的有参构造函数 "+str);
}
{
System.out.println(" JVMSons的构造代码块 ");
}
}父子关系:


根据上面的代码可以看到,我们的main方法、构造代码块、静态代码块都是没有顺序的放置,但是在输出结果里可以看到他们的执行是有固定顺序的,看下图:

在开发过程中可以根据具体业务去定义如何使用静态代码块、构造方法块、构造函数