请问关于 Java static 变量的问题?
ringa_lee
ringa_lee 2017-04-18 10:56:42
0
2
449
public class StaticTest {

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

    public static void main(String[] args) {
        a = "test";
        // I think the result is this is test
        // but the result is this is null, why?

        System.out.println(b);
    }


    //
    //  我本以为输出结果是 this is test
    // 没想到输出结果为 this is null, 这是什么原因

}
ringa_lee
ringa_lee

ringa_lee

Antworte allen(2)
巴扎黑

首先第一个:你在定义A变量时,就没有赋初值,所以A为NULL,然后得到B自然就是this is null
然后第二个:public static void main,编译器在编译这段代码时a,b先被main函数引用,你再更改a,a倒是被更改了,但b还是那个b,永远都是this is null。你需要明白静态函数运行的过程的意义。你的B没有动态被set,当然获得的就算那个静态b,而不会被动态编译。

黄舟

这是关于JVM的类初始化机制吧,字节码转为运行对象的三个过程装载,连接,初始化。。。其中连接的准备过程会给a赋予默认值null,因为 StaticTest 具有main方法,被设定为 JVM 启动时的启动类会执行主动调用,进行类的初始化,执行这两行代码 private static String a;private static String b = "this is " + a;所以b=this is null

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!