单例模型和静态加载综合运用(优酷面试题)
一:原题
1 /* 2 * 运行结果 3 * 2 4 * 1 5 */ 6 public class BookTest { 7 static BookTest book = new BookTest(); 8 static int a; 9 static int b = 0; 10 11 private BookTest() { 12 a++; 13 b++; 14 } 15 16 public static void main(String[] args) { 17 BookTest book = new BookTest(); 18 System.out.println(book.a); 19 System.out.println(book.b); 20 } 21 22 }
二:原题讲解
1 package com.heima.test; 2 3 /* 4 *程序执行时,jvm先加载Book类,然后加载new Book(),再加载静态变量a和静态变量b;但是 5 *此时并没有给a和b赋值(使用的是与其数据类型相对应的默认值,也即是两个静态变量a=0,b=0 6 *加载进内存),所以new Book()调用它的私有构造方法里输出a=1,b=1;然后给静态变量赋初值, 7 *也就是我们所给的值a不变,b又变成0(现在a=1,b=0);然后在主方法里又new Book()对象,再 8 *次调用构造方法,也就是a变成了2,b变成了1. 9 */ 10 11 /* 12 * 最后执行结果: 13 构造方法被调用了,调用之前: 14 a=0 b=0 15 构造方法调用之后: 16 a=1 b=1 17 静态代码块被调用了: 18 a=5; b=0 19 构造方法被调用了,调用之前: 20 a=5 b=0 21 构造方法调用之后: 22 a=6 b=1 23 6 24 1 25 */ 26 public class Book { 27 static Book book = new Book(); 28 static int a = 5; 29 static int b = 0; 30 static { 31 System.out.println("静态代码块被调用了:\na=" + a + ";\tb=" + b);// 也可以用Book.a和Book.b 32 } 33 34 private Book() { 35 System.out.println("构造方法被调用了,调用之前:"); 36 System.out.print("a=" + a + "\tb=" + b);// 也可以用Book.a和Book.b 37 a++; 38 b++; 39 System.out.println("\n构造方法调用之后:\na=" + a + "\tb=" + b); 40 } 41 42 public static void main(String[] args) { 43 Book book = new Book(); 44 System.out.println("a最后等于:" + book.a); 45 System.out.println("b最后等于:" + book.b); 46 } 47 48 }