为什么这个Java静态字段为空? [英] Why is this Java static field null?

查看:129
本文介绍了为什么这个Java静态字段为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class StaticTest {

    private static String a;
    private static String b = "this is " + a;

    public static void main(String[] args) {
        a = "test";

        System.out.println(b); // prints "this is null"
    }

}

我对 b 的价值感到困惑。我认为结果应该是这是测试,但结果是这是空的。为什么?

I'm confused about b's value. I think the result should be "this is test", but the result is "this is null". Why?

推荐答案

其他人已经解释了它的工作方式。

Others have explained why it works the way it does.

但是,有很多方法可以在引用时计算出值。

However, there are ways to to have the value calculated when you reference it.

private static String a;
private static Supplier<String> bSupplier = ()->"this is " + a;

public static void main(String[] args){
    a = "test";
    System.out.println(bSupplier.get()); //Prints "this is a test"
}

当你打电话给 bSupplier.get()计算该值。如果您更改 a 的值,并再次调用它,该值将反映新值。

When you call bSupplier.get() the value is calculated. If you change the value of a, and call it again, the value will reflect the new value.

不是你应该经常做的事情,但知道这一点很有用。

This is not something you should be doing often, but is useful to know.

这篇关于为什么这个Java静态字段为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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