gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:31 26 4
gpt4 key购买 nike

据我们所知,Java 对象的字段是这样初始化的:

  • boolean 变量得到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.

关于java - 哪种机制负责 Java 中字段的初始初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15772378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com