Creating an object in a static way

前端 未结 5 1245
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:01

    foo is instantiated during the static initialization of the class, and before sFlag was initialized, and the default value of a boolean is false.

    1. The class is loaded
    2. Foo is initialized to the instance

      2.a The instance member flag is initialized to the value of sFlag (false by default)

    3. sFlag is initialized to true

    Please refer to JLS §12.4 for more details.

提交回复
热议问题