这是演示静态块和静态方法的源代码。
class StaticDemo
{
static int count=10;
StaticDemo(){
count++;
}
static void display(){
System.out.println(count);
}
static{
System.out.println("Static Block written Before Main");
}
public static void main(String args[]){
StaticDemo t1=new StaticDemo();
StaticDemo t2=new StaticDemo();
StaticDemo.display();
t2.display();
}
static{
System.out.println("Static Block written After Main");
}
}
我期望输出
Static Block written Before Main
Static Block written After Main
11
12
而我得到的输出
Static Block written Before Main
Static Block written After Main
12
12
我知道静态块是要执行的第一组代码,因此是前两条语句的顺序。但是,当 JVM 创建 StaticDemo 类的对象 t1 时, count 的值不是递增到 11 ( 10+1 )吗?什么时候初始化/增量实际发生在程序中?谢谢!