gpt4 book ai didi

java - Java 中未初始化的类成员不会发出任何编译器错误。然而局部变量却可以。为什么?

转载 作者:行者123 更新时间:2023-12-02 02:09:47 24 4
gpt4 key购买 nike

考虑以下 Java 代码片段。它不会编译。

package temppkg;

final public class Main
{
private String x;
private int y;

private void show()
{
String z;
int a;

System.out.println(x.toString()); // Causes a NullPointerException but doesn't issue a compiler error.
System.out.println(y); // Works fine displaying its default value which is zero.
System.out.println(z.toString()); // Causes a compile-time error - variable z might not have been initialized.
System.out.println(a); // Causes a compile-time error - variable a might not have been initialized.
}

public static void main(String []args)
{
new Main().show();
}
}
<小时/>

为什么上面代码片段中声明的类成员(x 和 y)即使没有显式初始化并且只需要初始化局部变量,也不会发出任何编译时错误?

最佳答案

如有疑问,请检查 Java Language Specification (JLS)。

the introduction你会发现:

Chapter 16 describes the precise way in which the language ensures that local variables are definitely set before use. While all other variables are automatically initialized to a default value, the Java programming language does not automatically initialize local variables in order to avoid masking programming errors.

第一段chapter 16州,

Each local variable and every blank final field must have a definitely assigned value when any access of its value occurs....A Java compiler must carry out a specific conservative flow analysis to make sure that, for every access of a local variable or blank final field f, f is definitely assigned before the access; otherwise a compile-time error must occur.

默认值本身位于 section 4.12.5 中。该部分开头为:

Each class variable, instance variable, or array component is initialized with a default value when it is created.

...然后继续列出所有默认值。

JLS 确实不难理解,而且我发现自己越来越多地使用它来理解 Java 为何这样做……毕竟,它是 Java 圣经!

关于java - Java 中未初始化的类成员不会发出任何编译器错误。然而局部变量却可以。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57334788/

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