0
0

More than 3 years have passed since last update.

java staticイニシャライザとは

Posted at

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つのみではなく、複数定義する事も可能

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0