Properly declaring constants in Java
I have always declared constants like so;
Code Java:
private static final int MY_CONSTANT = 0;
But recently I have had reason to question the use of the static keyword in this declaration. Since it is final, do I even need to declare it static? Are there any repercussions for leaving out static? Are there any reasons I should leave in the static modifier in this context? Are there any costs associated with leaving the static clause?
Re: Properly declaring constants in Java
The repercussion of static in this context is a) you do not need to instantiate the class to get the value b) the value remains identical across classes c) Given static defines a class variable, it is not created with every instance of the class you create. Taking that forward:
Quote:
Since it is final, do I even need to declare it static?
If you access it from within a static context (for instance methods), then yes, and your compiler will tell you so.
Quote:
Are there any reasons I should leave in the static modifier in this context?
Again, do you need to access the variable from within a static context?
Quote:
Are there any costs associated with leaving the static clause?
Costs insofar as how you access the variable, and (albeit most likely miniscule and perhaps optimized by the compiler and/or JRE) costs of overhead when declared non-static. From the other perspective of not declaring it static, is there a reason you wish to have this variable for every instance?
Re: Properly declaring constants in Java
Quote:
Are there any repercussions for leaving out static?
The biggest one imaginable: if you live your life by the Java Code Conventions then you would have to change the case of your name:
Code Conventions for the Java Programming Language: 9. Naming Conventions