0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

javaオブジェクト生成とstaticの関係

Posted at

はじめに

Javaを使用していく中で、初回のみ実行したい処理 や オブジェクト生成ごとに実行したい処理 を書き分ける必要があります。
私自身、毎回混乱してしまうため、本記事では改めて整理します。

サンプルコード

今回は以下の種類の挙動について確認できるサンプルコードを作成しました.

  • フィールド
  • sataticフィールド
  • 初期化ブロック
  • static初期化ブロック
  • コンストラクタ
オブジェクトサンプル.java
public class Main {
    int i = 0;
    static int i_static = 0;
    {
        System.out.println("{}");
    }
    static {
        System.out.println("static{}");
    }
    Main() {
        System.out.println("Main(){}");
    }
    public void showNum() {
        System.out.println("i = " + ++i + "回目:static i = " + ++i_static +"回目");
    }
}
オブジェクト実行サンプル.java
public class Do {
    public static void main (String[] args) {
        Main main = new Main();
        main.showNum();

        main = new Main();
        main.showNum();

        Main main2 = new Main();
        main2.showNum();
    }
}

実行結果

.実行結果
static{}
{}
Main(){}
i = 1回目:static i = 1回目
{}
Main(){}
i = 1回目:static i = 2回目
{}
Main(){}
i = 1回目:static i = 3回目

static初期化ブロック,staticフィールドはクラスロード時に1回のみ実行されます.

クラス作成に関わらず,参照したタイミングで1回のみ実行されます.

初期化ブロック,フィールド,コンストラクタ(staticなし)はnewによるオブジェクト生成ごとに実行されます.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?