Why are local variables not initialized in Java?

后端 未结 15 922
不知归路
不知归路 2020-11-22 09:28

Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value,

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 09:40

    Moreover, in the example below, an exception may have been thrown inside the SomeObject construction, in which case the 'so' variable would be null and the call to CleanUp will throw a NullPointerException

    SomeObject so;
    try {
      // Do some work here ...
      so = new SomeObject();
      so.DoUsefulThings();
    } finally {
      so.CleanUp(); // Compiler error here
    }
    

    What I tend to do is this:

    SomeObject so = null;
    try {
      // Do some work here ...
      so = new SomeObject();
      so.DoUsefulThings();
    } finally {
      if (so != null) {
         so.CleanUp(); // safe
      }
    }
    

提交回复
热议问题