如果我使用默认的初始化或没有初始化,它会有所作为吗?
是否存在使用默认初始化的情况,例如:
int myValue;
要么
MyObject o = null;
与我根本不初始化变量的情况相比,我可以改变程序的行为吗?
我正在寻找一个例子。
必须在使用之前初始化局部变量。 这是由编译器强制执行的。
默认情况下,字段会初始化为与其类型关联的默认值(false,0,null)。 这是Java语言规范所要求的。
因此,将它们明确地初始化为默认值只会在大多数情况下增加噪音:
MyObject o = null;
什么都不做
MyObject o;
是的,可能会有区别,如本例所示。 它有点做作,但它归结为初始化发生的时间。
考虑以下课程:
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); } }
如果这会对您的代码库产生影响,那么您可能会担心更重要的事情!
在Java中,类的实例和静态成员字段被赋予默认值:primitives默认为0,对象为null,boolean为false。
但是,Java要求您在使用它们之前为本地变量赋值,这些变量在方法范围内声明。 此类变量没有默认值。
根据我的理解,没有这种情况。 Java规范要求根据以下规则默认初始化变量:
数字:0或0.0
布尔:虚假
对象引用:null
只要您考虑到这些规则进行编程,显式初始化为与上述相同的值将不会改变程序的行为。