以静态方式创建对象

编程入门 行业动态 更新时间:2024-10-11 17:29:54
本文介绍了以静态方式创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人能解释一下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.

更多推荐

以静态方式创建对象

本文发布于:2023-08-04 21:45:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1299881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   对象   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!