Java知識積累——靜態代碼塊,非靜態代碼塊,構造器的執行順序和次數


看如下程序

 1 class A {
 2    static{
 3       System.out.println("A static");
 4    }   
 5 
 6    {
 7       System.out.println("A not static"); 
 8    }   
 9 
10    public A(){
11       System.out.println("A new");
12    }
13 }
14 
15 class B extends A{
16    static{
17       System.out.println("B static");
18    }   
19 
20    {
21       System.out.println("B not static"); 
22    }  
23 
24    public B(){
25       System.out.println("B new");
26    }
27 } 
28 
29 public class MainTest {
30    public static void main(String[] args) {
31       A ab= new B();
32       ab= new B();
33    }
34 }

輸出如下:

A static

B static

A not static

A new

B not static

B new

A not static

A new

B not static

B new

 

結論: 

靜態代碼塊只有類首次加載進內存時調用一次,只此一次。

非靜態代碼塊,每次創建對象時,會在構造函數之前被調用。

構造函數,每次創建對象時,最后調用。

創建子類對象時,先創建父類對象,再創建子類對象。


免責聲明!

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



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