[java] java中的初始化順序

來源:互聯網
上載者:User

標籤:todo   rate   void   ini   log   public   string   method   pre   

先看程式:

 1 package init_cls; 2  3 class A{ 4  5     {System.out.println("i am in the class A!");} 6     static { System.out.println("static is the class A");} 7 } 8 public class init_cls { 9     {System.out.println("i am in the init_cls");}10     static{System.out.println("i am static in the init_cls class");}11     public static void main(String[] args) {12         // TODO Auto-generated method stub13         14         A a=new A();15         init_cls c=new init_cls();16     }17 18 }

運行結果為:

i am static in the init_cls class
static is the class A
i am in the class A!
i am in the init_cls

從結果中可以看到,當我們只是使用一個類中的方法的時候(在這裡使用的init_cls中的main),只初始化靜態變數,所以最先輸出:i am static in the init_cls class

之後當執行個體化一個類A的時候,先初始化其中的靜態域static ,所以輸出:static is the class A

                                        之後初始化非靜態域,所以輸出:i am in the class A!

最後,只有當我們執行個體化init_cls類的時候,才初始化了類A中的非靜態域,有了輸出:i am in the init_cls

 

這些和python中的初始化順序非常不同,在python中載入一個包的時候,會從上到下全部初始化,遇到語句時候全部執行

[java] java中的初始化順序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.