更新時(shí)間:2022-09-06 08:07:45 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1539次
使用初始化塊初始化實(shí)例變量。但是,靜態(tài)初始化塊只能初始化靜態(tài)實(shí)例變量。這些塊僅在加載類時(shí)執(zhí)行一次。一個(gè)類中可以有多個(gè)靜態(tài)初始化塊,按照它們?cè)诔绦蛑谐霈F(xiàn)的順序被調(diào)用。
下面給出了一個(gè)演示 Java 中的靜態(tài)初始化塊的程序:
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
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)