Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

oop - Why there is no local static variable in Java?

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 isn't it a bit weird to create a field for maintaining only one method's state?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have found the only solution.

Java dropped a number of complexities from C++, and this was one of them.

Static variables scoped to a function do nasty things to you in concurrency (e.g. strtok is a famously nasty one to use with pthreads, for exactly this reason).

In general, what you want is an object with state. The function in question should then have an object-level variable. Then you can create instances that each maintain state.

Much easier to understand/maintain/etc.

If you truly need to maintain state as a singleton, then static fields are it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...