Java中的非静态初始化块
使用初始化块初始化实例变量。这些代码块是在创建类对象时以及在调用类构造函数之前执行的。同样,在类中也不必有初始化块。
给出了一个演示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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短