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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP