クラスの完全装備から実行順序を見てみる
以下のサンプルコードを実行してみましょう。
このクラスでは5つのメッセージを以下の順序で表示します。
public class FullClassExample{ static int y; int x; { x = 0721; System.out.println("instance initializer: " + x); } static{ y = 0119; System.out.println("static initializer: " +y); } public FullClassExample(){ System.out.println("contracter begin"); } public void printMessage(){ System.out.println("method of Object begin"); } public static void main(String[] args){ System.out.println("begin to make Object"); FullClassExample fce = new FullClassExample(); fce.printMessage(); } }
これでクラスがメモリ上に展開される時必ず実行されるスタティックイニシャライザが真っ先に実行されるのがよくわかると思います。そしてnewした後の動きとして、まずインスタンスイニシャライザが実行され、そのあとにコンストラクタが実行されますね。