package com.ocr; class A { static { System.out.println("Static init A."); } { System.out.println("Instance init A."); } A() { System.out.println("Constructor A."); } } class B extends A { static { System.out.println("Static init B."); } { System.out.println("Instance init B."); } B() { System.out.println("Constructor B."); } } class C extends B { static { System.out.println("Static init C."); } { System.out.println("Instance init C."); } C() { System.out.println("Constructor C."); } } public class Main { static { System.out.println("Static init Main."); } { System.out.println("Instance init Main."); } public Main() { System.out.println("Constructor Main."); } public static void main(String[] args) { C c = new C(); // B b = new B(); } }
执行结果
Static init Main. Static init A. Static init B. Static init C. Instance init A. Constructor A. Instance init B. Constructor B. Instance init C. Constructor C.
结论:静态代码块优先于说有代码块执行,且从最顶级父类执行
顺序:父类的静态代码块->子类的静态代码块->父类的构造代码块->父类的构造方法->子类的构造代码块->子类的构造方法
来源:https://www.cnblogs.com/xyzxy/p/12592250.html