java中父类和子类初始化顺序

顺序

1. 父类中静态成员变量和静态代码块

2. 子类中静态成员变量和静态代码块

3. 父类中普通成员变量和代码块,父类的构造函数

4. 子类中普通成员变量和代码块,子类的构造函数

其中“和”字两端的按照代码先后顺序执行。

举例

先看代码:

Father类

[java] view plain copy
 
  1. public class Father {  
  2.     public String fStr1 = "father1";  
  3.     protected String fStr2 = "father2";  
  4.     private String fStr3 = "father3";  
  5.   
  6.     {  
  7.         System.out.println("Father common block be called");  
  8.     }  
  9.   
  10.     static {  
  11.         System.out.println("Father static block be called");  
  12.     }  
  13.   
  14.     public Father() {  
  15.         System.out.println("Father constructor be called");  
  16.     }  
  17.   
  18. }  
首先是Father类,该类有一个默认构造函数,有一个static的代码块,为了方便查看结果,还有一个普通代码块。

Son类

[java] view plain copy
 
  1. package com.zhenghuiyan.testorder;  
  2.   
  3. public class Son extends Father{  
  4.     public String SStr1 = "Son1";  
  5.     protected String SStr2 = "Son2";  
  6.     private String SStr3 = "Son3";  
  7.   
  8.     {  
  9.         System.out.println("Son common block be called");  
  10.     }  
  11.   
  12.     static {  
  13.         System.out.println("Son static block be called");  
  14.     }  
  15.   
  16.     public Son() {  
  17.         System.out.println("Son constructor be called");  
  18.     }  
  19.   
  20.     public static void main(String[] args) {  
  21.         new Son();  
  22.         System.out.println();  
  23.         new Son();  
  24.     }  
  25.   
  26. }  

Son类的内容与Father类基本一致,不同在于Son继承自Father。该类有一个main函数,仅为了测试用,不影响结果。

在main函数中实例化Son。

结果为:

[java] view plain copy
 
  1. Father static block be called  
  2. Son static block be called  
  3. Father common block be called  
  4. Father constructor be called  
  5. Son common block be called  
  6. Son constructor be called  
  7.   
  8. Father common block be called  
  9. Father constructor be called  
  10. Son common block be called  
  11. Son constructor be called  

总结:

1,在类加载的时候执行父类的static代码块,并且只执行一次(因为类只加载一次);

2,执行子类的static代码块,并且只执行一次(因为类只加载一次);

3,执行父类的类成员初始化,并且是从上往下按出现顺序执行(在debug时可以看出)。

4,执行父类的构造函数;

5,执行子类的类成员初始化,并且是从上往下按出现顺序执行。

6,执行子类的构造函数。

哔哔叭哔哄
原文地址:https://www.cnblogs.com/he-px/p/7750456.html