Java实例变量用方法初始化 [英] Java instance variables initialization with method
本文介绍了Java实例变量用方法初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对下面这段代码感到有些困惑:
I am a little bit confused about the following piece of code:
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
,但我认为这必须是一个编译器错误,因为当涉及到方法时,变量h应该没有被初始化 giveH()
。那么,编译是从上到下进行的吗?这为何有效?为什么 x
0的值而不是29?
The output here is 0 29
, but I thought that this has to be a compiler error, because the variable h should have not been initialized when it comes to the method giveH()
. So, does the compilation go through the lines from top to bottom? Why is this working? Why is the value of x
0 and not 29?
推荐答案
默认值 int
是 0
(参见here )。因为您在 h
之前初始化 x
, giveH
将返回int的默认值(例如0)。
The default value of int
is 0
(see here). Because you initialize x
before h
, giveH
will return the default value for a int (eg 0).
如果你这样切换订单
int h = 29;
int x = giveH();
输出将是
29 29
这篇关于Java实例变量用方法初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文