- static {
- // whatever code is needed for initialization goes there
- }
一个类中可以有任意个static block,用于初始化类变量(Class Variables),可以出现在类中的任意位置。Runtime system保证按在source code中出现的顺序调用它们。
也可以写一个private static 方法初始化class variables,好处在于:以后在需要的时候可以复用此方法进行重新初始化。
- class Whatever {
- public static varType myVar = initializeClassVar( ); // call the initialization method
- private static varType initializeClassVar( ) {
- // initialization code
- }
- }