Object initialization order

In this blog post I described order of object element’s initialization.

First of all class is initialized.

While this iteration static fields and class initializers are initialized in order of their declaration.

Static field is fields that have static keyword in declaration.

static Field staticField = new Field("I'm static field!");

Class initializer is code block in curly braces with static keyword.

static {
    System.out.println("I'm class initializer");
}

After class initialization - object is initialized.

First of all parent class constructor is invoked.

After that object fields and instance initializers in order of their declaration are invoked.

Instance initializer is code block in curly braces:

{
    System.out.println("I'm instance initializer");
}

At the end constructor is executed.

Example code

public class ClassAndObjectInitialization {
    public static void main(String[] args) {
        new Child();
    }
}

class Parent {
    Parent() {
        System.out.println("I'm parent!");
    }
}

class Child extends Parent {
    static Field staticField = new Field("I'm static field!");

    Field field = new Field("I'm field!");

    {
        System.out.println("I'm instance initializer");
        field = new Field("I'm field in instance initializer!");
    }

    static {
        System.out.println("I'm class initializer");
    }

    final static Field staticFinalField = new Field("I'm final static field!");

    final Field finalField = new Field("I'm Final field");

    public Child(){
        System.out.println("I'm child constructor!");
    }
}

class Field {
    public Field(String argument) {
        System.out.println(argument);
    }
}

Output:

I'm static field!
I'm class initializer
I'm final static field!
I'm parent!
I'm field!
I'm instance initializer
I'm field in instance initializer!
I'm Final field
I'm child constructor!

Run code

You can run code on https://ideone.com/NYDq8X.

Source code

You can find source code on GitHub

01.01.2019