筆試題中經常遇到的考察對static代碼塊的理解

          Posted on 2011-05-27 21:12 居健 閱讀(198) 評論(0)  編輯  收藏 所屬分類: Java
          近日來忙于找工作,雖是技術菜鳥,但特別希望能做與開發類的工作,因而筆試題也相對見了不少,幾乎每一家公司都會在考察java時出上一道與static代碼塊有關的題。這里列出一道經常見到的題(有時候許久不復習,還是會記憶模糊- -!)
          代碼1 SonClass.java
           1 /**
           2  * Created by IntelliJ IDEA.
           3  * User: solo
           4  * Date: 11-5-20
           5  * Time: 下午7:29
           6  * To change this template use File | Settings | File Templates.
           7  */
           8 public class SonClass extends FatherCLass
           9 {
          10     private  String sonName = "son";
          11     static
          12     {
          13         System.out.println("It's the son static field");
          14     }
          15     public static void main(String[] args)
          16     {
          17         SonClass sonClass = new SonClass();
          18         System.out.println("SonClass has been created");
          19     }
          20 }
          21 class FatherCLass
          22 {
          23 
          24     private String fatherName = getFatherName();
          25     static
          26     {
          27         System.out.println("It's the first father static field");
          28     }
          29     static
          30     {
          31         System.out.println("It's the second father static field");
          32     }
          33     private static  String getFatherName()
          34     {
          35         System.out.println("initialize the field:fatherName");
          36         return "BaBa";
          37     }
          38     public FatherCLass()
          39     {
          40         System.out.println("FatherClass has been created");
          41     }
          42 }
          43 
          當然了,題目一般就是要求寫出程序的輸出。

          這里主要涉及到三個主要的問題:
          1.static代碼塊初始化的順序
          2.子類繼承父類,在實例化時對父類構造函數的調用
          3.父類中fatherName什么時候被初始化

          我的理解如下:
          1.static代碼塊的初始化是在類編譯期完成的,其執行順序按照在類中出現的順序依次執行。因此首先輸出的應當是父類中的static塊,其次是子類中的static塊
          2.子類在實例化時,會調用父類構造函數,因此父類構造函數中的out一句會被執行
          3.在初始化時,變量先于構造函數
          因此,綜上,整個程序的輸出次序應當是:
          父類static塊--->子類static塊--->父類變量--->父類構造函數--->子類構造函數

          實際輸出結果如下:
          It's the first father static field
          It's the second father static field
          It's the son static field
          initialize the field:fatherName
          FatherClass has been created
          SonClass has been created

          ps:若文中有什么錯誤,歡迎批評指正。

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          posts - 0, comments - 0, trackbacks - 0, articles - 1

          Copyright © 居健

          主站蜘蛛池模板: 都昌县| 德江县| 五华县| 藁城市| 岢岚县| 杂多县| 迁安市| 奉新县| 华池县| 巴林右旗| 潜江市| 子洲县| 楚雄市| 丰原市| 志丹县| 汉沽区| 灵台县| 福贡县| 楚雄市| 天等县| 五华县| 常山县| 德昌县| 太湖县| 绍兴市| 东乡族自治县| 济宁市| 永济市| 蒲江县| 延吉市| 和田县| 永康市| 南丹县| 沈阳市| 仁化县| 南川市| 宜兰市| 太谷县| 辽阳市| 永嘉县| 明水县|