更新時間:2022-09-06 08:07:45 來源:動力節點 瀏覽1497次
使用初始化塊初始化實例變量。但是,靜態初始化塊只能初始化靜態實例變量。這些塊僅在加載類時執行一次。一個類中可以有多個靜態初始化塊,按照它們在程序中出現的順序被調用。
下面給出了一個演示 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("\nFor 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
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習