Why there is no local static variable in Java?

前端 未结 5 1875
星月不相逢
星月不相逢 2020-12-06 04:47

In C/C++ we use static local variables for maintaining a method\'s state. But why it is not supported in Java?

Yes, I can use an static field for this purpose. But i

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 05:07

    Some of the other answers show why you might not want to have this. But you can also ask why from a historical perspective.

    To answer this you have to start to see why C does have static local variables. C has much fewer means than Java and C++ to limit the scope of a variable, the only options for static data are 'inside the file' and 'everywhere'. So this provides an extra layer, to limit the scope.

    An important aspect of C++ is compatibility with, so it is allowed in C++ as well. But it doesn't need local static scope as much anymore, because there are many other means to limit scope of static data. The use is not popular in (modern) C++.

    Java merely takes a lot of inspiration from C/C++, it didn't have to worry about backwards compatibility, so it could be left out.

提交回复
热议问题