使用初始化块初始化实例变量。这些代码块是在创建类对象时以及在调用类构造函数之前执行的。同样,在类中也不必有初始化块。
给出了一个演示Java中的非静态初始化块的程序,如下所示:
public class Demo { static int[] numArray = new int[10]; { System.out.println("\nRunning non-static initialization block."); for (int i = 0; i < numArray.length; i++) { numArray[i] = (int) (100.0 * Math.random()); } } void printArray() { System.out.println("初始化的值是:"); 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("对于obj1:"); obj1.printArray(); Demo obj2 = new Demo(); System.out.println("对于obj2:"); obj2.printArray(); } }
输出结果
Running non-static initialization block. 对于obj1: 初始化的值是: 96 19 14 59 12 78 96 38 55 85 Running non-static initialization block. 对于obj2: 初始化的值是: 38 59 76 70 97 55 61 81 19 77