This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Actually I think what is important to understand here is that for accessing static variables/methods, we don't require an instance cause they are associated with the class. Hence they can be accessed from a static as well as a non static context. I think the rest of the rules/opinions are just derivations around that fact. Because they are not associated with an instance, static members ( let's refer to variables and methods as members ) are often used to create utility methods.
And we can have final static members. They are constants that don't change value. For example a double PI should always be 3.142. So we'd create a double pi as a constant ( a static, final member ).
For accessing instance members however we require an instance obviously cause they are instance members. Instances have a state and instance members are associated with that particular state ( through that instance ).
And hence we cannot access them from a static context without first creating an instance.
As Chan said, there is a final keyword for this. For primitives and Strings, it really does prevent you from changing the value. For other types, it prevents you from changing the reference, but not the value. For example, public static final List<String> doesn't prevent you from adding to the list. You'd need to make it an unmodifiable collection as well. Or honor the intent of the programmer in seeing the final.
Monica. Shiralkar wrote:But why is there nothing like a final keyword to disallow anyone changing static variables?
As everyone else has said, there is.
And I'll go one step further, and say that you should use it on every single static field you define - especially if they're public.
Why? Because, while public constants are not a bad thing, public variables almost invariably are.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here