3 回答
TA贡献1807条经验 获得超9个赞
在第一个代码示例中,a
是main
方法局部变量。在使用方法局部变量之前,需要对其进行初始化。
在第二个代码示例中,a
class成员变量是class,因此它将被初始化为default value。
TA贡献1852条经验 获得超7个赞
仔细阅读您的参考资料:
默认值
声明字段时,不一定总是需要分配值。 编译器会将已声明但未初始化的字段设置为合理的默认值。通常,此默认值将为零或null,具体取决于数据类型。但是,通常认为依赖于此类默认值是不好的编程风格。
下表总结了上述数据类型的默认值。
。。。
局部变量略有不同。编译器永远不会将默认值分配给未初始化的局部变量。如果您无法在声明它的地方初始化本地变量,请确保在尝试使用它之前为其分配一个值。访问未初始化的局部变量将导致编译时错误。
TA贡献1891条经验 获得超3个赞
这些是主要因素:
成员变量(默认为确定)
静态变量(默认为OK)
最终成员变量(未初始化,必须在构造函数上设置)
最终静态变量(未初始化,必须在静态块{}上设置)
局部变量(未初始化)
注意1:必须在每个实现的构造函数上初始化最终成员变量!
注意2:您必须在构造函数本身的块内初始化最终成员变量,而不是调用用于对其进行初始化的其他方法。例如,这是无效的:
private final int memberVar;
public Foo() {
//invalid initialization of a final member
init();
}
private void init() {
memberVar = 10;
}
注3:数组是Java中的对象,即使它们存储原语也是如此。
注意4:初始化数组时,其所有项目均设置为默认值,而与成为成员数组或本地数组无关。
我将附上一个代码示例,介绍上述情况:
public class Foo {
//static and member variables are initialized to default values
//primitives
private int a; //default 0
private static int b; //default 0
//objects
private Object c; //default NULL
private static Object d; //default NULL
//arrays (Note: they are objects too, even if they store primitives)
private int[] e; //default NULL
private static int[] f; //default NULL
//what if declared as final?
//primitives
private final int g; //not initialized, MUST set in constructor
private final static int h; //not initialized, MUST set in a static {}
//objects
private final Object i; //not initialized, MUST set in constructor
private final static Object j; //not initialized, MUST set in a static {}
//arrays
private final int[] k; //not initialized, MUST set in constructor
private final static int[] l; //not initialized, MUST set in a static {}
//initialize final statics
static {
h = 5;
j = new Object();
l = new int[5]; //elements of l are initialized to 0
}
//initialize final member variables
public Foo() {
g = 10;
i = new Object();
k = new int[10]; //elements of k are initialized to 0
}
//A second example constructor
//you have to initialize final member variables to every constructor!
public Foo(boolean aBoolean) {
g = 15;
i = new Object();
k = new int[15]; //elements of k are initialized to 0
}
public static void main(String[] args) {
//local variables are not initialized
int m; //not initialized
Object n; //not initialized
int[] o; //not initialized
//we must initialize them before usage
m = 20;
n = new Object();
o = new int[20]; //elements of o are initialized to 0
}
}
添加回答
举报