Creating an object in a static way

前端 未结 5 1238
Happy的楠姐
Happy的楠姐 2020-12-22 23:52

Could anyone explain how Java executes this code? I mean the order of executing each statement.

public class Foo
{
    boolean flag = sFlag;
    static Foo f         


        
5条回答
  •  醉话见心
    2020-12-23 00:23

    The general order of initialization operations is (after the class is loaded and before first use):

    1. Static (class) code blocks in order it appears in the code,
    2. Object code blocks in order it appears in the code (initialization blocks and assignments).
    3. Constructors

    Certainly I don't refer constructors and functions body as a code block above .

    I don't know how about final static fields. It looks like they follow the rules of static fields and they cannot be referenced before declaration despite previous comments that they are initialized at compilation step. If they are referenced before there is a compilation error:

    Example.java:8: illegal forward reference
            System.err.println("1st static block j=" + j);
    

    Maybe final static fields can be initialized and compiled into the class file but this is not a general rule and they still cannot be referenced before declaration.

    Example code to check initialization order:

    class Example {    
    
        final static int j = 5;
    
        {
            System.err.println("1st initializer j=" + j);
        }
    
        static {
            System.err.println("1st static block j=" + j);
        }
    
        static {
            System.err.println("2nd static block j=" + j);
        }
    
        final static java.math.BigInteger i = new java.math.BigInteger("1") {    
            {
                System.err.println("final static anonymous class initializer");
            }
        };
    
        Example() {
            System.err.println("Constructor");
        }
    
        static {
            System.err.println("3nd static block j=" + j);
        }
    
        {
            System.err.println("2nd initializer");
        }
    
        public static void main(String[] args) {
            System.err.println("The main beginning.");
            Example ex = new Example();
            System.err.println("The main end.");
        } 
    }
    

    The above code snipset prints:

    1st static block j=5
    2nd static block j=5
    final static anonymous class initializer
    3nd static block j=5
    The main beginning.
    1st initializer j=5
    2nd initializer
    Constructor
    The main end.
    

提交回复
热议问题