Java 中的靜態初始化塊
例項變數使用初始化塊進行初始化。然而,靜態初始化塊只能初始化靜態例項變數。這些塊只能在類被載入時執行一次。一個類中可以有多個靜態初始化塊,它們會按照在程式中出現的順序被呼叫。
一個展示 Java 中靜態初始化塊的程式如下
示例
public class Demo { static int[] numArray = new int[10]; static { System.out.println("Running static initialization block."); for (int i = 0; i < numArray.length; i++) { numArray[i] = (int) (100.0 * Math.random()); } } void printArray() { System.out.println("The initialized values are:"); for (int i = 0; i < numArray.length; i++) { System.out.print(numArray[i] + " "); } System.out.println(); } public static void main(String[] args) { Demo obj1 = new Demo(); System.out.println("For obj1:"); obj1.printArray(); Demo obj2 = new Demo(); System.out.println("
For obj2:"); obj2.printArray(); } }
輸出
Running static initialization block. For obj1: The initialized values are: 40 75 88 51 44 50 34 79 22 21 For obj2: The initialized values are: 40 75 88 51 44 50 34 79 22 21
廣告