Sunday, January 14, 2007

Why Java doesn’t allow static variables inside methods?

As you may already know that static variables in Java are scoped to the class. I couldn’t find the exact answer as to why it is this way, but my guess is that when you make a variable static, your intension is to have that variable available across multiple calls to the method where you want to have the static variable. Under this circumstance, the scope of the variable is over and above the method scope. It’s like using a private member variable. The approach taken by Java may improve the clarity, but it may violate encapsulation requirements.

No comments: