是否存在使用默认初始化的情况,例如:
int myValue;
或
MyObject o = null;
与我根本没有初始化变量的情况相比,可以改变程序的行为吗?
我正在寻找一个例子。
答案 0 :(得分:8)
必须在使用之前初始化局部变量。这是由编译器强制执行的。
字段默认初始化为与其类型关联的默认值(false,0,null)。这是Java语言规范所要求的。
因此,将它们明确地初始化为默认值只会在大多数情况下增加噪音:
MyObject o = null;
除了
之外什么都不做MyObject o;
答案 1 :(得分:2)
是的,可能会有区别,如本例所示。这有点做作,但它归结为初始化发生的时间。
考虑以下课程:
import java.lang.reflect.Field;
public class base {
protected base(int arg) throws Exception {
Field f = getClass().getDeclaredField("val");
System.out.println(f.get(this));
f.set(this, 666);
}
}
以下两个扩展它的类。 test1
显式设置为0:
public class test1 extends base {
int val=0; // Explicitly set to 0
public test1() throws Exception {
super(0);
}
public static void main(String argv[]) throws Exception {
System.out.println(new test1().val);
}
}
test2
离开它:
public class test2 extends base {
int val; // just leave it to be default
public test2() throws Exception {
super(0);
}
public static void main(String argv[]) throws Exception {
System.out.println(new test2().val);
}
}
运行这些给出:
javac test1.java && java test1
0
0
但对于第二种情况:
javac test2.java && java test2
0
666
这巧妙地说明了不同的行为,唯一的变化是该字段的= 0
。
通过拆解第一个案例可以看出原因:
import java.io.PrintStream;
public synchronized class test1 extends base
{
int val;
public test1()
throws Exception
{
super(0);
val = 0; // Note that the the explicit '= 0' is after the super()
}
public static void main(String astring[])
throws Exception
{
System.out.println(new test1().val);
}
}
如果这会对您的代码库产生影响,那么您需要担心更多的事情!
答案 2 :(得分:1)
在Java中,类的实例和静态成员字段被赋予默认值:primitives默认为0,对象为null,boolean为false。
但是,Java要求您在使用它们之前为本地变量赋值,这些变量在方法范围内声明。这种变量没有默认值。
答案 3 :(得分:0)
据我所知,没有这种情况。 Java规范要求根据以下规则默认初始化变量:
数字:0或0.0
布尔人:假的 对象引用:null
只要您考虑到这些规则进行编程,明确初始化为与上述相同的值将不会改变程序的行为。