Are fields initialized before constructor code is run in Java?

后端 未结 5 2216
梦谈多话
梦谈多话 2020-11-22 06:39

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\".



        
5条回答
  •  时光说笑
    2020-11-22 07:15

    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

    1. Call the constructor of Z
    2. It triggers the default constructor of X
    3. First line of X constructor new Y() is called.
    4. Print Y
    5. Print X
    6. Call the first line in constructor Z new Y()
    7. Print Y
    8. Print Z

    All the instance variables are initialized by using constructor statements.

提交回复
热议问题