Java 中的非靜態初始化塊


使用初始化塊初始化例項變數。在建立類物件並呼叫類建構函式之前執行這些塊。另外,類中不必有初始化塊。

以下是一個展示 Java 中非靜態初始化塊的程式

示例

 線上演示

public class Demo {
   static int[] numArray = new int[10];
   {
      System.out.println("
Running non-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 non-static initialization block.
For obj1:
The initialized values are:
96 19 14 59 12 78 96 38 55 85
Running non-static initialization block.
For obj2:
The initialized values are:
38 59 76 70 97 55 61 81 19 77

更新時間:2019 年 7 月 30 日

2K+ 瀏覽

開啟你的 職業之旅

透過完成此課程獲得認證

開始學習
廣告