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
Java, What is the difference between assigning null to object and just declaration
提问by ???
What is difference between :
有什么区别:
Object o = null
; andObject 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 values
in 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 variable
need not be assigned null
as those take null
as 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
有关更多详细信息,您可以参考此链接