Can anyone explain the output of following program? I thought constructors are initialized before instance variables. So I was expecting the output to be \"XZYY\".
If you look at the decompiled version of the class file
class X {
Y b;
X() {
b = new Y();
System.out.print("X");
}
}
class Y {
Y() {
System.out.print("Y");
}
}
public class Z extends X {
Y y;
Z() {
y = new Y();
System.out.print("Z");
}
public static void main(String args[]) {
new Z();
}
}
You can find that the instance variable y is moved inside the constructor, so the execution sequence is as follows
ZXX constructor new Y() is called.new Y()YAll the instance variables are initialized by using constructor statements.