Why are local variables not initialized in Java?

后端 未结 15 706
不知归路
不知归路 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:39

    (It may seem strange to post a new answer so long after the question, but a duplicate came up.)

    For me, the reason comes down to this this: The purpose of local variables is different than the purpose of instance variables. Local variables are there to be used as part of a calculation; instance variables are there to contain state. If you use a local variable without assigning it a value, that's almost certainly a logic error.

    That said, I could totally get behind requiring that instance variables were always explicitly initialized; the error would occur on any constructor where the result allows an uninitialized instance variable (e.g., not initialized at declaration and not in the constructor). But that's not the decision Gosling, et. al., took in the early 90's, so here we are. (And I'm not saying they made the wrong call.)

    I could not get behind defaulting local variables, though. Yes, we shouldn't rely on compilers to double-check our logic, and one doesn't, but it's still handy when the compiler catches one out. :-)

提交回复
热议问题