Java中未初始化的变量和成员 [英] Uninitialized variables and members in Java

查看:172
本文介绍了Java中未初始化的变量和成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

public class TestClass {

    private String a;
    private String b;

    public TestClass()
    {
    a = "initialized";
    }

    public void doSomething()
    {
    String c;

        a.notify(); // This is fine
    b.notify(); // This is fine - but will end in an exception
    c.notify(); // "Local variable c may not have been initialised"
    }

}

我不明白。 b从未初始化,但会产生与c相同的运行时错误,这是一个编译时错误。为什么局部变量和成员之间存在差异?

I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?

编辑:让成员保密是我最初的意图,问题仍然存在......

Edit: making the members private was my initial intention, and the question still stands...

推荐答案

明确分配的规则非常困难(阅读JLS 3rd Ed的第16章)。在字段上强制执行明确的赋值是不切实际的。就目前而言,甚至可以在初始化之前观察最终字段。

The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised.

这篇关于Java中未初始化的变量和成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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