Why attempt to print uninitialized variable does not always result in an error message

前端 未结 6 1859
滥情空心
滥情空心 2020-12-24 10:28

Some may find it similar to the SO question Will Java Final variables have default values? but that answer doesn\'t completely solve this, as that question doesn\'t directl

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 11:14

    The difference is that in the first case you are calling System.out.println from initializer block so the block which is invoked before constructor. In the first line

    System.out.println(x);
    

    variable x is not yet initialized so that you get compilation error.

    But in the second case you call instance method which doesn't know if variable has already been initialized so you don't have compilation error and you can see the default value for x

提交回复
热议问题