Java中未初始化的类成员不会发出任何编译器错误。然而局部变量呢。为什么? [英] Uninitialized class members in Java do not issue any compiler errors. local variables however do. Why?

查看:189
本文介绍了Java中未初始化的类成员不会发出任何编译器错误。然而局部变量呢。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider the following code snippet in Java. It won't compile.

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 )不会发出任何编译时错误,即使它们没有显式初始化并且只需要初始化局部变量?


Why do the class members (x and y) declared in the above code snippet not issue any compile-time error even though they are not explicitly initialized and only local variables are required to be initialized?

推荐答案

如有疑问,请检查 Java语言规范(JLS)。

When in doubt, check the Java Language Specification (JLS).

介绍你会发现:


第16章描述了语言确保$的确切方式b $ b在使用前必须设置局部变量。虽然所有其他
变量都自动初始化为默认值,但Java
编程语言不会自动初始化局部变量
,以避免掩盖编程错误。

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.

第16章陈述,


每个局部变量和每个空白的最终字段必须具有绝对$ b当对其值的任何访问发生时,$ b分配值.... Java编译器
必须执行特定的保守流分析,以确保每次访问本地变量或空白最终字段时的
f,f
在访问之前是明确分配的;否则必须发生编译时
错误。

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.

默认值本身在第4.12.5节。该部分打开:

The default values themselves are in section 4.12.5. The section opens with:


每个类变量,实例变量或数组组件都是
,当它是默认值时初始化创建。

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

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

...and then goes on to list all the default values.

JLS实际上并不难理解,我发现自己越来越多地使用它来理解Java为什么会这样做......毕竟,这是Java圣经!

The JLS is really not that hard to understand and I've found myself using it more and more to understand why Java does what it does...after all, it's the Java bible!

这篇关于Java中未初始化的类成员不会发出任何编译器错误。然而局部变量呢。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆