gpt4 book ai didi

java - 声明一个类类型的变量而不初始化它

转载 作者:行者123 更新时间:2023-11-29 08:43:46 24 4
gpt4 key购买 nike

我在某处读到,在阅读 System.out.print 时,在 System 类中,有一个 'out' 声明为 PrintStream 类类型静态变量如下: public static final PrintStream out;

这让我产生了一个疑问,如果我们只声明一个特定类类型的变量而不通过不调用任何构造函数来初始化它,到底会发生什么?在上面的示例中,“out”被声明为静态和最终的,但我正在寻找一个通用的答案。

最佳答案

This invoked a question in me that what exactly happens if we just declare a variable of a certain class type and not initialize it by not calling any constructor?

然后像任何其他字段一样,它以默认值开始 - 对于引用类型(类、接口(interface)、枚举),它是 null 引用。来自 section 4.12.5 of the JLS :

Every variable in a program must have a value before its value is used:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
  • 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.

System.out 有点特殊 - 它是最终的,但可以通过 System.setOut 进行更改。我会尽量避免基于此概括任何其他行为。

关于java - 声明一个类类型的变量而不初始化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009284/

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