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
广告