在java類中,是先執行類的構造函數還是先執行類的私有非靜態變量


舉例子:

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實例化過  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM