Java 類初始化順序

self_control發表於2015-08-16
Java 類初始化順序為
1、父類靜態欄位初始化
2、子類靜態欄位初始化
3、父類普通欄位初始化
4、父類構造器執行
5、子類普通欄位初始化
6、類構造器執行

點選(此處)摺疊或開啟

  1. import java.util.Random;

  2. public class InitOrder {
  3.     public static int getInt(String info){
  4.         System.out.println(info);
  5.         Random random = new Random(47);
  6.         return random.nextInt();
  7.     }
  8.     public static void main(String [] args){
  9.         new Son();
  10.         // 關注 Father 的 filed 與 Son 的sonFiled的初始化
  11.     }
  12. }

  13. class Son extends Father{
  14.     private int sonFiled = InitOrder.getInt("子類普通欄位初始化");
  15.     private static int sonStaticFiled = InitOrder.getInt("子類靜態欄位初始化");
  16.     public Son(){
  17.         this.sonFiled = InitOrder.getInt("子類構造器執行");
  18.     }
  19.     public int getSonFiled() {
  20.         return sonFiled;
  21.     }
  22.     public void setSonFiled(int sonFiled) {
  23.         this.sonFiled = sonFiled;
  24.     }
  25.     public static int getSonStaticFiled() {
  26.         return sonStaticFiled;
  27.     }
  28.     public static void setSonStaticFiled(int sonStaticFiled) {
  29.         Son.sonStaticFiled = sonStaticFiled;
  30.     }

  31.     
  32. }
  33. class Father{
  34.     private int filed = InitOrder.getInt("父類普通欄位初始化");
  35.     private static int staticFiled = InitOrder.getInt("父類靜態欄位初始化");
  36.     public Father(){
  37.         this.filed = InitOrder.getInt("父類構造器執行");
  38.     }
  39.     public int getFiled() {
  40.         return filed;
  41.     }
  42.     public void setFiled(int filed) {
  43.         this.filed = filed;
  44.     }
  45.     public static int getStaticFiled() {
  46.         return staticFiled;
  47.     }
  48.     public static void setStaticFiled(int staticFiled) {
  49.         Father.staticFiled = staticFiled;
  50.     }
  51.     
  52. }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/30066956/viewspace-1773078/,如需轉載,請註明出處,否則將追究法律責任。

相關文章