我正在阅读Java,我正在摸索为什么System.out.println("a: " + a);
不会产生编译错误。 a
在哪里初始化?
public class localVariableEx {
public static int a;
public static void main(String[] args) {
int b;
System.out.println("a: " + a);
System.out.println("b: " + b); //Compilation error
}
}
答案 0 :(得分:9)
the JLS § 4.12.5 Initial Values of Variables(强调我的)中描述了相关的相关规则:
因此,当实例变量(例如a
)自动获得默认值时,局部变量(例如b
)不会获得一个,除非编译器可以验证值已分配给他们。
答案 1 :(得分:8)
b
是仅在方法范围中定义的变量,因此编译器可以知道之前没有人初始化它,但a
是一个可能在其他地方初始化的公共变量。
答案 2 :(得分:0)
a
属于原始类型int
,会立即初始化,这意味着:
静态类成员:在加载类时获取初始化(大部分时间,在main()
之前,但它取决于何时加载类)。< / p>
class S {
static int a;
}
非静态类成员:在对象出现时进行初始化。 (大部分时间在new
之后,但还有其他更高级的方法来创建新对象。)
class S {
int a;
}
本地变量:应该在首次使用之前在方法的范围内初始化。
class S {
void foo() {
int b = 0;
}
}
经过更正后编辑...