Opinionated Final Variables in Java
I use final whenever it is appropriate.
Static final variables has two chances to initialize
- On declaration
- In static initializer block
static final Long MY_ID = 111L; static final Long YOUR_ID; static { YOUR_ID = 222L; }
Non-static final variables has three chagnes to initialize
- On declaration
- In initializer block
-
In the constructor
Note: any final field must be initialized before the constructor completes.
final Long MY_ID = 111L; final Long YOUR_ID; final Long ANOTHER_ID; { // this block has to be upper than constructor ANOTHER_ID = 333L; } MyClass() { YOUR_ID = 222L; }
Final Primitive Type is real final
If you try to reassign a value to an initialized final primitive variable, you will get this:
Error: java: cannot assign a value to final variable i
Final Reference Type has only the reference final
final
is only about the reference itself, and not about the contents of the referenced object.
void withCat (final Cat cat) {
cat.setId(2);
}
public static void main(String[] args) {
final Cat cat = new Cat();
cat.setId(1);
}
Question and Answer
-
Improved performance?
Not always, not really. -
Why use
final
?
Should use final based on clear design and readability. -
When must use? You have to mark something final so you can access it from within an anonymous inner class.
-
Benefits
At first, it kind of looks awkward to see a lot of final keywords in your code, but pretty soon you’ll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on.