staticイニシャライザとは
クラスのロード時に一度だけ実行されるコードブロックのこと。
例)
staticSample.java
class Sample{
public static void main( String args[] ){
System.out.println( "今年で" + Nenrei.age + "歳になる。");
}
}
class Nenrei{
static int age = 25;
static{
age ++;
}
}
上記の実行結果
今年で26歳になる。
Nenreiクラスのstaticフィールドであるageが呼び出された際に、
staticイニシャライザに定義されている
age ++
が実行され、ageが+1される。
また、staticイニシャライザは1つのみではなく、複数定義する事も可能