在java類中,是先執行類的建構函式還是先執行類的私人非靜態變數

來源:互聯網
上載者:User

標籤:log   順序   []   靜態代碼塊   print   執行   blog   system   instance   

舉例子:

package test_instance;public class TestClassLoaderTime {                public TestClassLoaderTime(){              System.out.println("構造器執行");         }              {               System.out.println("靜態代碼塊執行");         }         static Demo2 demo2 = new Demo2();                private Demo3 demo3 = new Demo3();                public static void main(String[] args) {                System.out.println("main方法執行");                new TestClassLoaderTime();                System.out.println("TestClassLoaderTime執行個體化過");          }             }  


執行結果:

Initialization the Demo2.....
main方法執行
靜態代碼塊執行
Initializaiton the Demo3....
構造器執行
TestClassLoaderTime執行個體化過

所以是按照如下順序執行的:

1.Demo2的建構函式執行   (靜態屬性)
2.main方法執行  
3.靜態代碼塊執行  
4.Demo3的建構函式執行    (非靜態屬性)
5.構造器執行               
6.TestClassLoaderTime執行個體化過  

 

在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.