我有以下场景包 com.example.test;
public class StaticTest {
public static final String STATIC_VAR="Static Var";
static{
System.out.println("Static Block Called....");
}
public static void init(){}
}
package com.example.test;
public class MainClass {
public static void main(String[] args) {
System.out.println("Test static initialization");
String staticvar =StaticTest.STATIC_VAR;
System.out.println("Referred static variable--> "+ staticvar);
System.out.println("Calling static method");
StaticTest.init();
System.out.println("Static method invoked");
}
}
我得到的输出是
Test static initialization
Referred static variable--> Static Var
Calling static method
**Static Block Called....**
Static method invoked
我期待的输出是
Test static initialization
**Static Block Called....**
Referred static variable--> Static Var
Calling static method
Static method invoked
我在想,只要我提到静态变量,静态块就会被执行。
有什么解释吗?