I always heard
from other java developers that a Final variable is a constant that will never “change”
its value, like:
Final int pi= 3,14 ;
...Then if we try to change the [pi] value we will get a compiler error :
Pi=0 //
compiler error -> "The final local variable i cannot be
assigned. It must be blank and not using a compound
assignment"
assigned. It must be blank and not using a compound
assignment"
That’s true
for primitive type in java but what’s
about the variable that point to a reference, does the object will really never change?
Let’s see
the definition from the source :
“Once a
final
variable has been assigned, it
always contains the same value. If a final
variable holds a reference to an
object, then the state of the object may be changed by operations on the
object, but the variable will always refer to the same object. »
So as text says,
if the variable HOLDS a reference to an object, the behavior will not be as like as a
primitive type, …..Hmm…that’s interesting…let’s do some practicing to unveil this concept.
Note : Don't waste your time by copy and paste the code, you can download the whole project from the link at the end of the article (in the very last sentence!!!!).
Note : Don't waste your time by copy and paste the code, you can download the whole project from the link at the end of the article (in the very last sentence!!!!).
We create
[Person]
class as follow:
public class Person { String lastName; String firstName; int age; public Person(String lastName, String firstName, int age) { this.lastName = lastName; this.firstName = firstName; this.age = age; } }In the source file you'll find more code in the
[Person]
class(Getters, Setters...)
The main
class:
….So as we can see the final keyword bring a tricky behavior when the variable points to reference :
public class MainApp { public static void main(String[] args) { final Person p1; final Person p2 = new Person("Ahmed", "SAMIR",20); p1 = new Person("Omar", "BEHLOUL",38); p1.age = 26; // ok no error p2.firstName = p1.firstName; // coz we're changing the fields and not the reference // p1 = p2; // compiler error --> "The final local variable p1 may already have been assigned" // p1 can't refer another object (p2) } }
….So as we can see the final keyword bring a tricky behavior when the variable points to reference :
- You can’t refer it to another object after the first assignment.
- The member/fields of the final variable can be freely changed without any restriction.
However
this attitude of final variable can be a benefit for your program but can be
against you too , and it mainly depends on your designing of the application...so be careful!!
Hey...one minute, just to remember you that final keyword exists also for:
Hey...one minute, just to remember you that final keyword exists also for:
- Class to stop inheritance.
- Method to stop overridden.
You can download the source code from here...Good testing!
No comments:
Post a Comment