java 类加载-初始化顺序

时间:2021-10-16 19:37:54
代码: packagecom.lczyfz.istep.modules.test.service;
classRoot { static { System.out.println("Root的静态初始化块"); } { System.out.println("Root的普通初始化块"); } publicRoot(){ System.out.println("Root的无参数构造器"); } }

classMid extendsRoot { static { System.out.println("Mid的静态初始化块"); } { System.out.println("Mid的普通初始化块"); } publicMid(){ System.out.println("Mid的无参数构造器"); } publicMid(String msg){ this(); System.out.println("Mid的带参数构造器,其参数值:"+ msg); } }
classLeaf extendsMid{ static{ System.out.println("Leaf的静态初始化块"); } { System.out.println("Leaf的普通初始化块"); } publicLeaf(){ super("疯狂java讲义"); System.out.println("执行Leaf的构造器"); } }
public classTest{ public static voidmain(String[] args){ newLeaf(); newLeaf(); } }


答案: Root的静态初始化块 Mid的静态初始化块 Leaf的静态初始化块
Root的普通初始化块 Root的无参数构造器 Mid的普通初始化块 Mid的无参数构造器
Mid的带参数构造器,其参数值:疯狂java讲义 Leaf的普通初始化块 执行Leaf的构造器
Root的普通初始化块 Root的无参数构造器 Mid的普通初始化块 Mid的无参数构造器 Mid的带参数构造器,其参数值:疯狂java讲义 Leaf的普通初始化块 执行Leaf的构造器

============================================================ 静态初始化块和声明静态Field时所指定的初始值都是该类的初始化代码,它们的执行顺序与源程序中的排列顺序相同。 代码: packagecom.lczyfz.istep.modules.test.service;
/** * Created by hpp on 2017/4/5. */
classBase{ static{ System.out.println("Base static"); } publicBase(){ System.out.println("Base init"); } } public classTest1 extendsBase{ Stringm = ""; staticString n; static{ System.out.println("A static"); } publicTest1(String mValue,String nValue){ m= mValue; n= nValue; } public voidprint(){ System.out.println(m+ " "+ n); }
public static voidmain(String[] args){ Test1 a1 =new Test1("M1","N1"); Test1 a2 =new Test1("M2","N2"); a1.print(); a2.print(); } 答案: Base static A static Base init Base init M1 N2 M2 N2
public static voidmain(String[] args){ Test1 a1 =new Test1("M1","N1"); a1.print(); Test1 a2 =new Test1("M2","N2"); a2.print(); }
答案: Base static A static Base init M1 N1 Base init M2 N2
}