看看程序输出什么?
public class A { private boolean shouldPrint = true; static { System.out.println("hi"); } public A() {} public void show() { if(shouldPrint) System.out.println("hello"); System.out.println("java"); shouldPrint = false; } public static void main(String[] args) { A a = new A(); a.show(); a.show(); a = new A(); a.show(); // hi hello java java hello java } }
其实这里面主要考察了下面几点:
1. java 中static区域初始化
2. if语句的作用域
3. a = new A();的含义