1. 程式人生 > >Java之靜態代碼塊

Java之靜態代碼塊

詳細 struct clas zhang 構造 依次 pub str 靜態方法

有一些情況下,有些代碼需要在項目啟動的時候就執行,則需要使用靜態代碼塊,這種代碼是主動執行的。
Java中的靜態代碼塊是在虛擬機加載類的時候,就執行的,而且只執行一次。如果static代碼塊有多個,JVM將按照它們在類中出現的先後順序依次執行它們,每個代碼塊只會被執行一次。

代碼的執行順序:
  1. 主調類的靜態代碼塊
  2. 對象父類的靜態代碼塊
  3. 對象的靜態代碼塊
  4. 對象父類的非靜態代碼塊
  5. 對象父類的構造函數
  6. 對象的非靜態代碼塊
  7. 對象的構造函數

//靜態代碼塊
static{
...;
}

//靜態代碼塊
{
...;
}

代碼舉例:
  1 package staticblock;
  2 
  3 public class
StaticBlockTest { 4 //主調類的非靜態代碼塊 5 { 6 System.out.println("StaticBlockTest not static block"); 7 } 8 9 //主調類的靜態代碼塊 10 static { 11 System.out.println("StaticBlockTest static block"); 12 } 13 14 public StaticBlockTest() { 15 System.out.println("constructor StaticBlockTest");
16 } 17 18 public static void main(String[] args) { 19 // 執行靜態方法前只會執行靜態代碼塊 20 Children.say(); 21 System.out.println("----------------------"); 22 23 // 全部驗證舉例 24 Children children = new Children(); 25 children.getValue(); 26 } 27 }
28 29 /** 30 * 父類 31 */ 32 class Parent { 33 34 private String name; 35 private int age; 36 37 //父類無參構造方法 38 public Parent() { 39 System.out.println("Parent constructor method"); 40 { 41 System.out.println("Parent constructor method--> not static block"); 42 } 43 } 44 45 //父類的非靜態代碼塊 46 { 47 System.out.println("Parent not static block"); 48 name = "zhangsan"; 49 age = 50; 50 } 51 52 //父類靜態代碼塊 53 static { 54 System.out.println("Parent static block"); 55 } 56 57 //父類有參構造方法 58 public Parent(String name, int age) { 59 System.out.println("Parent constructor method"); 60 this.name = "lishi"; 61 this.age = 51; 62 } 63 64 public String getName() { 65 return name; 66 } 67 68 public void setName(String name) { 69 this.name = name; 70 } 71 72 public int getAge() { 73 return age; 74 } 75 76 public void setAge(int age) { 77 this.age = age; 78 } 79 } 80 81 /** 82 * 子類 83 */ 84 class Children extends Parent { 85 //子類靜態代碼塊 86 static { 87 System.out.println("Children static block"); 88 } 89 90 //子類非靜態代碼塊 91 { 92 System.out.println("Children not static block"); 93 } 94 95 //子類無參構造方法 96 public Children() { 97 System.out.println("Children constructor method"); 98 } 99 100 101 public void getValue() { 102 //this.setName("lisi"); 103 //this.setAge(51); 104 System.out.println(this.getName() + " " + this.getAge()); 105 } 106 107 public static void say() { 108 System.out.println("子類靜態方法執行!"); 109 } 110 }

執行結果:

StaticBlockTest static block
Parent static block
Children static block
子類靜態方法執行!
----------------------
Parent not static block
Parent constructor method
Parent constructor method--> not static block
Children not static block
Children constructor method
zhangsan 50

  

詳細:http://uule.iteye.com/blog/1558891




Java之靜態代碼塊