以静态方式创建对象 [英] Creating an object in a static way
本文介绍了以静态方式创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能解释一下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 andsFlag
is false - The first static variable initializer (
foo
) runs:- A new instance of
Foo
is created - The instance variable initializer for
flag
executes - currentlysFlag
is false, so the value offlag
is false
请注意,如果
sFlag
被宣布为final
,则将其视为一个编译时常量,此时对它的所有引用基本上都会内联到true
,所以foo.flag
也是如此。Note that if
sFlag
were declared to befinal
it would be treated as a compile-time constant, at which point all references to it would basically be inlined totrue
, sofoo.flag
would be true too.这篇关于以静态方式创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- A new instance of
-
查看全文