Java 中的静态初始化块
实例变量使用初始化块进行初始化。然而,静态初始化块只能初始化静态实例变量。这些块只能在类被加载时执行一次。一个类中可以有多个静态初始化块,它们会按照在程序中出现的顺序被调用。
一个展示 Java 中静态初始化块的程序如下
示例
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("
For 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
广告