以静态方式创建对象 [英] Creating an object in a static way

查看:130
本文介绍了以静态方式创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下Java如何执行这段代码吗?我的意思是执行每个语句的顺序。

Could anyone explain how Java executes this code? I mean the order of executing each statement.

public class Foo
{
    boolean flag = sFlag;
    static Foo foo = new Foo();
    static boolean sFlag = true;

    public static void main(String[] args)
    {
        System.out.println(foo.flag);
    }
}

输出:

false


推荐答案


  • 类初始化开始。最初, foo 为空, sFlag 为false

  • 第一个静态变量初始化程序( foo )运行:

    • Foo 已创建

    • 执行 flag 的实例变量初始化程序 - 当前 sFlag 是假的,所以 flag 的值为false

      • Class initialization starts. Initially, foo is null and sFlag is false
      • The first static variable initializer (foo) runs:
        • A new instance of Foo is created
        • The instance variable initializer for flag executes - currently sFlag is false, so the value of flag is false
        • 请注意,如果 sFlag 被宣布为 final ,则将其视为一个编译时常量,此时对它的所有引用基本上都会内联到 true ,所以 foo.flag 也是如此。

          Note that if sFlag were declared to be final it would be treated as a compile-time constant, at which point all references to it would basically be inlined to true, so foo.flag would be true too.

          这篇关于以静态方式创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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