Hello Lili Hello Lili - 1 year ago 77
Java Question

Java - What is the order of intialization in this code?

In the following Java code, the Insect class is inherited by the Beetle class.

class Insect {

private int i = 9;
protected int j;

Insect() {
System.out.println("i = " + i + ", j = " + j);
j = 39;
private static int x1
= printInit("static Insect.x1 initialized");

static int printInit(String s) {

return 47;

public class Beetle extends Insect {

private int k = printInit("Beetle.k initialized");

public Beetle() {
System.out.println("k = " + k);
System.out.println("j = " + j);
private static int x2
= printInit("static Beetle.x2 initialized");

public static void main(String[] args) {
System.out.println("Beetle constructor");
Beetle b = new Beetle();

The output is somehow comfusing.

static Insect.x1 initialized

static Beetle.x2 initialized

Beetle constructor

i = 9, j = 0

Beetle.k initialized

k = 47 j = 39

What is the order of initialization in this particular example?

Why is x2 initialized immediatly after x1? And why is the first line of the main method (
System.out.println("Beetle constructor");
), executed after x1 and x2 intializaton. So comfusing.

I know that the derived class constructor automatically calls the base class constructor (unless it has parameters and you'd use the super keyword). I know that variables are initialized before the constructor, and that static variables are initialized before other variables.

Answer Source

x1 and x2 are static. This means that they are initialized when the class is loaded. Since the main method is in Beetle, the class has to be loaded before invoking main. This is why x1 and x2 initialization is the first thing you see. Not sure about why the order of those two is as it is.

Now you are calling main and System.out.println("Beetle constructor"); is executed. Then it calls Beetle() which implicitly calls super() (aka Insect()) first. This prints i = 9, j = 0 because i is 9 and j has not been initialized at that point, which means it has the default int value 0.

Now j is set to 39 and the flow continues in Beetle(). This now initializes the fields of Beetle, in your case k. So when it comes to the explicit code in Beetle(), k is initialized to 47 and j to 39 by the super constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download