Initialization of instance fields vs. local variables

前端 未结 7 565
余生分开走
余生分开走 2020-11-27 06:07

I have always been wondering about why in the following example it is OK to not initialize the instance field (relying that it will have its default value)

7条回答
  •  心在旅途
    2020-11-27 06:23

    It's a compiler limitation. The compiler tries to prevent you using an unassigned variable wherever it can, which is a good thing as using uninitialised variables used to be a common source of bugs in old C code.

    The compiler can't however know whether the instance variable is initialised before you hit that method call because it could be set by any other method, which may be called in any order by external code.

提交回复
热议问题