Java类初始化顺序

发布时间:2020-06-22 11:00:25
阅读量:37
作者:猎维人工智能培训
Java面试题

结论

基类静态代码块,基类静态成员字段(并列优先级,按照代码中出现的先后顺序执行,且只有第一次加载时执行)

——>派生类静态代码块,派生类静态成员字段(并列优先级,按照代码中出现的先后顺序执行,且只有第一次加载时执行)

——>基类普通代码块,基类普通成员字段(并列优点级,按代码中出现先后顺序执行)

——>基类构造函数

——>派生类普通代码块,派生类普通成员字段(并列优点级,按代码中出现先后顺序执行)

——>派生类构造函数

代码验证

class Log {

   public static String initLog(String log) { System.out.println(log);return null; }

}


/**

 * 基类

*/


class Base {

   static { System.out.println("Base Static Block 1"); }

   private static String staticValue = Log.initLog("Base Static Fiels");

   static { System.out.println("Base Static Block 2"); }

   { System.out.println("Base Normal Block 1"); }

   private String value = Log.initLog("Base Normal Field");

   { System.out.println("Base Normal Block 2"); }

   Base() { System.out.println("Base Constructor"); }

}


/**

 * 派生类

 */

public class Derived extends Base {

   static { System.out.println("Static Block 1"); }

   private static String staticValue = Log.initLog("Static Fiels");

   static { System.out.println("Static Block 2"); }

   { System.out.println("Normal Block 1"); }

   private String value = Log.initLog("Normal Field");

   { System.out.println("Normal Block 2"); }

   Derived() { System.out.println("Derived Constructor"); }


/**

 * 主线程

 */

public static void main(String[] args) {

   Derived derived = new Derived();

}


控制台结果输出:

Base Static Block 1

Base Static Fiels

Base Static Block 2

Static Block 1

Static Fiels

Static Block 2

Base Normal Block 1

Base Normal Field

Base Normal Block 2

Base Constructor

Normal Block 1

Normal Field

Normal Block 2

Derived Constructor

 

更多资讯