2013-05-07 22 views

回答

31

它取決於您聲明變量的範圍。例如,局部變量沒有default values在這種情況下,你將不得不分配手動,其中在實例變量的情況下分配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 
    } 
} 
1

如所提到的,對象引用作爲instance variable不需要被分配null那些採取null作爲默認值。但是局部變量必須被初始化,否則你會得到編譯錯誤,說The local variable s may not have been initialized

欲瞭解更多詳情,請參閱this link