posted 19 years ago
As M Beck discusses, the reason for the final is so it does not get changed in any code. Attempts to do so will result in a compile time error. As for the static, the static doesn't mean so much that it is used "throughout the program" (that would be a loose interpretation). It ultimately means that only a single instance of that variable is created in memory.
Lets say I an object MyThing, and we want to define a constant MAX_VALUE in MyThing. So I do the following:
If my program creates 1000 instances of MyThing, there will be 1000 separate int's created in memory, all holding the same value (and since they are final, none can be changed). Each will have a single reference pointer to it (the MAX_VALUE of each of the 1000 MyThing instances). This seems like a waste of memory since they are all holding the same value. If however, I change that to a static attribute:
Now, whether I create 1, 1000, or 1 million instances of MyThing, only one int is stored in memory. Therefore I am saving memory space (and I believe improving performance slightly, but I'm not sure on that.)
The other advantage of a static attribute, is I do not need to instantiate an instance of the object in order to access its value. So if somewhere else in my program I need to know the MAX_VALUE for MyThing, I can write MyThing.MAX_VALUE as in:
instead of having to go thorough the expensive process of creating an instance of the object first:
So in the above case, since we are declaring something as final, such that it will not change, and we therefore know each instance will have the same value, why not make it static to save memory, and make it available without needing to instantiate an object?
There are times where you will make an attribute static without making it final. Let's say I have an object for which I know a specific attribute will be the same for each instance of the object, but it may change (and thus is not final). For example, if I have a BankAccount class with an "interestRate" attribute. I want all instances of my BankAccount object to have the same interest rate, but that rate changes daily. If I create a non-static attribute:
When the interest rate changes, I have to change the interestRate attribute for all instances of BankAccount. If there are thousands of instance, it becomes a very expensive process and lowers performance. (Not to mention I'm using a several thousand times more memory then I need to be since they all hold the same value).
However, if I make interestRate static:
Now I can change the interest rate for all accounts, whether 1, 1000, or 1 million, in a single call:
It is much less expensive, and thus better performance, to call a method one time then to call it 10 thousand, or 1 million times.
I hope that helps you to understand static and final and why we would make the constant both static and final in your code; and when you would make something only static.
[ March 05, 2005: Message edited by: Mark Vedder ]