哪种机制负责Java中字段的初始初始化

据我们所知, Java对象的字段以这种方式初始化:

>布尔变量得到false
>其他原始类型(如int,byte,long)得到0
>对象获取null

我的问题是哪种机制(方法)正在做这项工作,何时这样做?

当JVM创建类的新实例时,将完成这些初始化.见 Creation of new class instances部分.它指出:

Whenever a new class instance is created, memory space is allocated
for it with room for all the instance variables declared in the class
type and all the instance variables declared in each superclass of the
class type, including all the instance variables that may be hidden
(§8.3).

If there is not sufficient space available to allocate memory for the
object, then creation of the class instance completes abruptly with an
OutOfMemoryError. Otherwise, all the instance variables in the new
object, including those declared in superclasses, are initialized to
their default values
(§4.12.5).

每种类型的实例变量的默认值如下:

  • For type byte, the default value is zero, that is, the value of (byte)0.
  • For type short, the default value is zero, that is, the value of (short)0.
  • For type int, the default value is zero, that is, 0.
  • For type long, the default value is zero, that is, 0L.
  • For type float, the default value is positive zero, that is, 0.0f.
  • For type double, the default value is positive zero, that is, 0.0d.
  • For type char, the default value is the null character, that is, '\u0000'.
  • For type boolean, the default value is false.
  • For all reference types (§4.3), the default value is null.
相关文章
相关标签/搜索