对实例变量的初始化感到困惑
我正在准备 SCJP 考试,在做一些模拟测试时,我遇到了这个:
它询问以下内容的输出是什么:
class TestClass
{
int i = getInt();
int k = 20;
public int getInt() { return k+1; }
public static void main(String[] args)
{
TestClass t = new TestClass();
System.out.println(t.i+" "+t.k);
}
}
我认为它会是 21 20
,因为 ti 会调用getInt,然后将 k 增加到 21。
但是,答案是 1 20
。我不明白为什么它会是1,有人能解释一下吗?
I'm studying up for the SCJP exam, upon doing some mock tests I came across this one :
It asks what is the output of the following :
class TestClass
{
int i = getInt();
int k = 20;
public int getInt() { return k+1; }
public static void main(String[] args)
{
TestClass t = new TestClass();
System.out.println(t.i+" "+t.k);
}
}
I thought it would be 21 20
, since t.i would invoke getInt, which then increments k to make 21.
However, the answer is 1 20
. I don't understand why it would be 1, can anyone shed some light on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
变量是从上到下初始化的。
发生的情况是这样的:
i
和k
都具有(默认)值0
。getInt()
计算的值(当时为0 + 1
)被分配给i
20
被分配给k
1 20
被打印。好读:
The variables are initialized from top to bottom.
This is what happens:
i
andk
have the (default) value0
.getInt()
(which at the time is0 + 1
) is assigned toi
20
is assigned tok
1 20
is printed.Good reading:
jvm会这样,
1.从上到下对非静态成员进行标识
2.从上到下执行非静态变量和块
3.执行构造函数......
第一步jvm将提供默认值..此时变量处于readindirectly write only状态..
jvm will follows like this,
1.identification for non-static members from top to bottom
2.executing non-static variables and blocks from top to bottom
3.executing the constructor......
in the first step jvm will provide default values..on that time variables in readindirectly write only state..