Creating an object in a static way

前端 未结 5 1228
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:08

    • Class initialization starts. Initially, foo is null and sFlag is false
    • The first static variable initializer (foo) runs:
      • A new instance of Foo is created
      • The instance variable initializer for flag executes - currently sFlag is false, so the value of flag is false
    • The second static variable initializer (sFlag) executes, setting the value to true
    • Class initialization completes
    • main runs, printing out foo.flag, which is false

    Note that if sFlag were declared to be final it would be treated as a compile-time constant, at which point all references to it would basically be inlined to true, so foo.flag would be true too.

提交回复
热议问题