Java,将null赋给object和声明之间的区别是什么

有什么区别:

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

有人可以回答我吗?

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

 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 } } 

如上所述,对象引用作为instance variable不需要指定为null因为它们将null作为默认值。 但必须初始化局部变量,否则会出现编译错误,说明The local variable s may not have been initialized

有关详细信息,请参阅此链接