请问关于 Java static 变量的问题?
ringa_lee
ringa_lee 2017-04-18 10:56:42
[Java讨论组]
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

全部回复(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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号