Cannot figure out code execution order

64 Views Asked by At

I have the following code.

class X {
    X(){
        super();
        System.out.println("X()");
    }
}

class Y extends X {
    Y(){
        super();
        System.out.println("Y()");
    }
}

class Z extends Y {
    Z(){
        super();
        System.out.println("Z()");
    }

    public static void main(String args[]){

        Z z1 = new Z();
    }
}

And I get the output

X()
Y()
Z()

All fine. It's the way, it's supposed to be. And when I make an static object of X() in the class Z like follows

class X {
    X(){
        super();
        System.out.println("X()");
    }
}

class Y extends X {
    Y(){
        super();
        System.out.println("Y()");
    }
}

class Z extends Y {
    static X x1 = new X();
    Z(){
        super();
        System.out.println("Z()");
    }   

    public static void main(String args[]){

        Z z1 = new Z();
    }
}

X()
X()
Y()
Z()

The output is ok because the static instances are loaded to the RAM at first. But when I make the static object instance like this

X x1 = new X();

I get the following output

X()
Y()
X()
Z()

Which really confuses me. As for my knowledge, I should get the following output

X()
Y()
Z()
X()

At the first the Z object will be instantiated and the X object should be instantiated at last. In this case, it instantiates at third. Why is that? Is there any special concept that applies here?

0

There are 0 best solutions below