为什么这个Java静态字段为空?

Jia*_*Wan 6 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"
    }

}
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*wes 6

其他人已经解释了为什么它的工作方式.

但是,有一些方法可以在引用时计算值.

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"
}
Run Code Online (Sandbox Code Playgroud)

当你调用bSupplier.get()该值时,计算出来.如果更改了值a,并再次调用它,则该值将反映新值.

这不是你应该经常做的事情,但知道有用.


小智 4

您将字符串 a 添加到字符串 b,但字符串 a 尚未定义。您应该在定义它之后将其添加到字符串 b。

private static String a = "test";
private static String b = "this is a " + a;
public static void main(String [] args){
  System.out.println(b);
}
Run Code Online (Sandbox Code Playgroud)