JVM类的加载顺序
前阵子看到阿里巴巴的一提面试题是关于java类的加载顺序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.mikey.demo.Test; class FatherVariable{ static { System.out.println("FatherVariable Static Constructor Code"); } { System.out.println("FatherVariable Constructor Code"); } public FatherVariable() { System.out.println("FatherVariable Constructor Method"); } } class ChildVariable{ static { System.out.println("ChildVariable Static Constructor Code"); } { System.out.println("ChildVariable Constructor Code"); } public ChildVariable() { System.out.println("ChildVariable Constructor Method"); } } class Father{ static FatherVariable fatherVariable = new FatherVariable(); static { System.out.println("Father Static Constructor Code"); } { System.out.println("Father Constructor Code"); } public Father() { System.out.println("Father Constructor Method"); } } class Child extends Father { static ChildVariable childVariable = new ChildVariable(); static { System.out.println("Child Static Constructor Code"); } { System.out.println("Child Constructor Code"); } public Child() { System.out.println("Child Constructor Method"); } } public class Clazz { public static void main(String[] args) { new Child(); //父类静态变量 //FatherVariable Static Constructor Code //FatherVariable Constructor Code //FatherVariable Constructor Method //父类静态代码块 //Father Static Constructor Code //子类静态变量 //ChildVariable Static Constructor Code //ChildVariable Constructor Code //ChildVariable Constructor Method //子类静态代码块 //Child Static Constructor Code //父类构造代码块 //Father Constructor Code //父类构造方法 //Father Constructor Method //子类构造代码块 //Child Constructor Code //子类构造方法 //Child Constructor Method } }
图解分析
实例化顺序
父类静态变量
↓
父类静态代码块
↓
子类静态变量
↓
子类静态代码块
↓
父类构造代码块
↓
父类构造方法
↓
子类构造代码块
↓
子类构造方法
//父类静态变量 //FatherVariable Static Constructor Code //FatherVariable Constructor Code //FatherVariable Constructor Method //父类静态代码块 //Father Static Constructor Code //子类静态变量 //ChildVariable Static Constructor Code //ChildVariable Constructor Code //ChildVariable Constructor Method //子类静态代码块 //Child Static Constructor Code //父类构造代码块 //Father Constructor Code //父类构造方法 //Father Constructor Method //子类构造代码块 //Child Constructor Code //子类构造方法 //Child Constructor Method
结论:
1.带继承的类:
先按照声明顺序初始化基类静态变量和静态代码块,接着按照声明顺序初始化子类静态变量和静态代码块,
而后按照声明顺序初始化基类普通变量和普通代码块,然后执行基类构造函数,接着按照声明顺序初始化子类普通变量和普通代码块
最后执行子类构造函数。
合群是堕落的开始 优秀的开始是孤行