On the initialization order of members in java classes

Keywords: Java

What is the initialization order of the members after the class is created?

Don't think about inheritance first

package com;

public class DemoOne {
    /**
     * On the initialization order of classes
     */
    //Regardless of inheritance structure
    private static int a;
    private String  str="I'm assigned a value";
    {
        System.out.println("3 Enter code block  str ===="+ str);
        System.out.println("4 Go to normal code block");


    }
    static{
        System.out.println("1 Static code block a==="+a);
        //here a The initial value 0 indicates that the static variable executes before the static code block because of the sequence of the code
        //  Compile and report errors     System.out.println("str ===="+ str);
        System.out.println("2 Enter static code block");


    }
    public DemoOne(){
        System.out.println("5 Enter constructor");
        System.out.println(" Constructor str===="+str);
        System.out.println("a===="+a);

    }

    public static void main(String[] args) {
        new  DemoOne();
    }

}

The output after running the program is:

1 static code block a = 0
2 enter static code block
str = = = in code block 3
4 into normal code block
5 enter the constructor
str = = = I'm assigned a value in the constructor
a====0

To verify that the order of static members is determined by the order of the code, static variables and static block order are adjusted

 

package com;

public class DemoOne {
    /**
     * On the initialization order of classes
     */
    //Regardless of inheritance structure
    static{
        //  Compile and report errors     System.out.println("str ===="+ str);
        System.out.println("1 Enter the first static code block");
    }
    private static int a;
    static{
        System.out.println("2 Enter the second static block a===="+a);
    }
    private String  str="I'm assigned a value";
    {
        System.out.println("3 Enter code block  str ===="+ str);
        System.out.println("4 Go to normal code block");


    }

    public DemoOne(){
        System.out.println("5 Enter constructor");
        System.out.println(" Constructor str===="+str);
        System.out.println("a===="+a);

    }

    public static void main(String[] args) {
        new  DemoOne();
    }

}

The output result is:

1 enters the first static code block
2 enter the second static block a = ==== 0
3 enter the code block str = = = I have been assigned a value
4 into normal code block
5 enter the constructor
str = = = I'm assigned a value in the constructor
a====0

From the output result, we can see that the static block and the sequence of static variables have changed after adjusting the sequence

Posted by micklerlop on Mon, 02 Dec 2019 06:53:33 -0800