Java 中的非静态初始化块
java 8object oriented programmingprogramming
使用初始化块初始化实例变量。这些块在创建类对象时以及调用类构造函数之前执行。此外,类中不必有初始化块。
以下是演示 Java 中非静态初始化块的程序:
示例
public class Demo { static int[] numArray = new int[10]; { System.out.println("
正在运行非静态初始化块。"); 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(); } }
输出
正在运行非静态初始化块。 对于 obj1: 初始化值为: 96 19 14 59 12 78 96 38 55 85 正在运行非静态初始化块。 对于 obj2: 初始化值为: 38 59 76 70 97 55 61 81 19 77