话不多说,直接上代码:
/*** @Author: YuShiwen* @Date: 2020/11/17 9:01 PM* @Version: 1.0*/classRoot{ static{ System.out.println("Root static block"); } { System.out.println("Root no static block"); } publicRoot(){ super(); System.out.println("Root no parameter"); } } classMidextendsRoot{ static{ System.out.println("Mid static block"); } { System.out.println("Mid no static block"); } publicMid(){ super(); System.out.println("Mid no parameter"); } publicMid(Stringmsg){ this(); System.out.println("Mid constructor:"+msg); } } classLeafextendsMid{ static{ System.out.println("Leaf static block"); } { System.out.println("Leaf no static block"); } publicLeaf(){ super("YuShiwen"); System.out.println("Leaf no parameter"); } } publicclassLeafTest { publicstaticvoidmain(String[] args) { newLeaf(); System.out.println(); newLeaf(); } }
输出结果:
RootstaticblockMidstaticblockLeafstaticblockRootnostaticblockRootnoparameterMidnostaticblockMidnoparameterMidconstructor:YuShiwenLeafnostaticblockLeafnoparameterRootnostaticblockRootnoparameterMidnostaticblockMidnoparameterMidconstructor:YuShiwenLeafnostaticblockLeafnoparameterProcessfinishedwithexitcode0
代码分析:
可以看出,静态代码块内的语句由父类到子类最先执行,且只执行一次,这是因为静态代码块虽类的加载而加载;
之后每创建一次对象的时候,由父及子,先执父类中的普通代码块,再执行父类中的构造器,然后在执行子类中的普通代码块,再执行子类中的构造器。