一篇文章讲清楚父类子类的加载顺序

使用两个类,一个父类,一个子类

父类代码:

 1 public class Parent {
 2     public static int i = 10;
 3     private int j = 15;
 4 
 5     static {
 6         System.out.println("parent 静态代码块,无静态变量");
 7     }
 8 
 9     static {
10         i = i + 100;
11         System.out.println("parent 静态代码块,有静态变量,i=" + i);
12     }
13 
14     {
15         System.out.println("parent 代码块,无静态变量");
16     }
17 
18     {
19         j = j + 200;
20         System.out.println("parent 代码块,有静态变量,j=" + j);
21     }
22 
23     public Parent() {
24         System.out.println("parent 构造方法");
25     }
26 
27 }

子类代码:

 1 public class Child extends Parent {
 2     public static int m = 26;
 3     private int n = 37;
 4 
 5     static {
 6         System.out.println("child 静态代码块,无静态变量");
 7     }
 8 
 9     static {
10         m = m + 300;
11         System.out.println("child 静态代码块,有静态变量,m=" + m);
12     }
13 
14     {
15         System.out.println("child 代码块,无静态变量");
16     }
17 
18     {
19         n = n + 400;
20         System.out.println("child 代码块,有静态变量, n=" + n);
21     }
22 
23     public Child(){
24         System.out.println("child 构造方法");
25     }
26 
27     public static void main(String[] args) {
28         Child child = new Child();
29     }
30 }

执行结果:

parent 静态代码块,无静态变量
parent 静态代码块,有静态变量,i=110
child 静态代码块,无静态变量
child 静态代码块,有静态变量,m=326
parent 代码块,无静态变量
parent 代码块,有静态变量,j=215
parent 构造方法
child 代码块,无静态变量
child 代码块,有静态变量, n=437
child 构造方法

 

结论:

1. 若存在继承关系,而且父类和子类中都存在静态代码块、静态变量、构造代码块、构造方法

2. 先是父类静态代码块和静态变量,静态代码块和静态变量的初始化顺序 是谁在前谁先加载

3. 再是子类静态代码块和静态变量,静态代码块和静态变量的初始化顺序 是谁在前谁先加载

4. 再是父类构造代码块,父类构造方法

5. 再是子类构造代码块,父类构造方法

posted @ 2019-12-26 21:47  zhuitian  阅读(2176)  评论(0编辑  收藏  举报