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 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短