java – What is the class field or constructor initialized first?

Question:

Reading Eckel's book, I came across one point that I cannot understand. The following code is presented:

import static net.mindview.util.Print.*;

class Insect {
    private int i = 9;
    protected int j;
    Insect() {
        print("i = " + i + ", j = " + j);
        j = 39;
    }
    private static int x1 = printInit("static Insect.x1 initialized");
    static int printInit(String s) {
        print(s);
        return 47;
    }
}

public class Beetle extends Insect {
    private int k = printInit("Beetle.k initialized");
    public Beetle() {
        print("k = " + k);
        print("j = " + j);
    }
    private static int x2 = printInit("static Beetle.x2 initialized");
    public static void main(String[] args) {
        print("Beetle constructor");
        Beetle b = new Beetle();
    }
}

OUTPUT:

static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39

I always thought that before calling the constructor, the fields of the class must be initialized so that if you access an un-initialized variable in the constructor, you don't get an exception. Following this logic, the "Beetle.k initialized" output should have been after the "Beetle constructor" output. I'm sorry to help figure it out. Thank you.

Answer:

The initialization order is as follows:

  1. Parent static members
  2. Static elements of the successor
  3. Parent global variables
  4. Parent constructor
  5. Successor global variables
  6. Successor constructor

Example

class Insect {
    private int i = 9;                                                 [9]
    protected int j;                                                   [10]
    Insect() {                                                         [8]
        print("i = " + i + ", j = " + j);                              [11]
        j = 39;                                                        [12]
    }
    private static int x1 = printInit("static Insect.x1 initialized"); [2]
    static int printInit(String s) {                                   [3]
        print(s);
        return 47;
    }
}

public class Beetle extends Insect {
    private int k = printInit("Beetle.k initialized");                 [13]
    public Beetle() {                                                  [7]
        print("k = " + k);                                             [14]
        print("j = " + j);                                             [15]
    }
    private static int x2 = printInit("static Beetle.x2 initialized"); [4]
    public static void main(String[] args) {                           [1]
        print("Beetle constructor");                                   [5]
        Beetle b = new Beetle();                                       [6]
    }
}
Scroll to Top