what is the point of having an instance variable as final?
isn´t it better to have that variable set as a static final variable then?
cause if it can't be changed by any of the objects, then it's the same as a class (static) variable, right?
A variable declared final can never be change it's value once it has been initialized. Since in immutable class you never need to change the property/field state, so it is better to make it final.
C++ Programming final is a non-access modifier for Java elements. The final modifier is used for finalizing the implementations of classes, methods, and variables. A final instance variable can be explicitly initialized only once. At time of declaration.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.
Nope. static
means it's the same across all instances of the class. final
means it's not assignable after its initial assignment. So two instances could have different values for a non-static final variable.
There are many reasons you might want to make a variable final; one of the best is clarity. If I read a method and notice that the foo is final, I don't have to worry about where it's changing down below - because it isn't; it can't. I can make more changes to code with final variables with less concern ("did I change the value of foo before or after bar, and does it matter?") because I know that some variables aren't subject to change. It also focuses my attention on the variables that are subject to change - and they're the ones that deserve more attention.
Two reasons:
1) From the class design view, it allows a programmer to rely on the fact that the field will not change since instantiation - so called "immutable object" (where applied to class members, not the object's reference). Java tutorial says:
Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.
Immutable objects are a cornerstone of various programming styles, e.g. pure functional programming.
2) The second reasons is JVM optimizations. If all fields are final, then JVM knows the object's state can't be changed, and thus it can make many optimizations, e.g. ommiting thread safety checks etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With