Java,将null分配给对象和仅声明有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16415848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:54:05  来源:igfitidea点击:

Java, What is the difference between assigning null to object and just declaration

javanulldeclaration

提问by ???

What is difference between :

有什么区别:

  • Object o = null; and
  • Object o;(just declaration)
  • Object o = null; 和
  • Object o;(只是声明)

Can anyone please answer me?

有人可以回答我吗?

回答by PermGenError

It depends on the scope where you declare the variable. For instance, local variablesdon't have default valuesin which case you will have to assign nullmanually, where as in case of instance variablesassigning null is redundant since instance variables get default values.

这取决于您声明变量的范围。例如, 局部变量没有,default values在这种情况下您必须手动分配空值,而在实例变量分配空值的情况下是多余的,因为实例变量获得默认值。

public class Test {
    Object propertyObj1;
    Object propertyObj2 = null; // assigning null is redundant here as instance vars get default values 

    public void method() {
        Object localVariableObj1;
        Object localVariableObj1.getClass(); // illegal, a compiler error comes up as local vars don't get default values

        Object localVariableObj2 = null;
        Object localVariableObj2.getClass(); // no compiler error as localVariableObj2 has been set to null

        propertyObj1.getClass(); // no compiler error
        propertyObj2.getClass(); // no compiler error
    }
}

回答by Madhusudan Joshi

As mentioned, object reference as instance variableneed not be assigned nullas those take nullas default value. But local variables must be initialized otherwise you will get compilation error saying The local variable s may not have been initialized.

如前所述,instance variable不需要分配对象引用,null因为它们null作为默认值。但是局部变量必须被初始化,否则你会得到编译错误说The local variable s may not have been initialized.

For more details you can refer this link

有关更多详细信息,您可以参考此链接