【发布时间】:2016-02-13 15:14:57
【问题描述】:
我对下面这段代码有点困惑:
public class Test{
int x = giveH();
int h = 29;
public int giveH(){
return h;
}
public static void main(String args[])
{
Test t = new Test();
System.out.print(t.x + " ");
System.out.print(t.h);
}
}
这里的输出是0 29,但我认为这一定是编译器错误,因为当涉及到方法giveH()时,变量h应该没有被初始化。那么,编译是否从上到下逐行进行?为什么这行得通?为什么x的值是0而不是29?
【问题讨论】:
-
这是因为做事的顺序。 1/ 事物声明 2/ 定义(如果需要)。像这样考虑:
int h; int x; x = giveH(); h = 29;
标签: java compilation initialization instance-variables