If instance variable is set final its value can not be changed like
public class Final {
private final int b;
Final(int b) {
this.b = b;
Note:- When you declare an object reference as final, it means that it will always point to the same object on heap to which it was initialized.
If cacheMap which is declared as final is passed as parameter to another class then error is not shown for final if I change its reference. Why it is so?
1.) Java is pass by value so when you write cc.setConditionMap(cacheMap
) where cacheMap
is an object reference (Note:- cacheMap
is not an object itself, it is just a reference) then you are just passing the address of the object on heap to setConditionMap(cacheMap)
, now inside setConditionMap(cacheMap)
, conditionMap
is initialized with the value of cacheMap
(the value of cache Map is the address of Map Object). Now after this step both conditionMap
and cacheMap
refers to the same object on heap. But the catch is that you can again set the value of conditionMap
so that it points to some other map object on heap but cacheMap
will always point to the same Map Object.
2.) Declaring a variable as final doesn't means that object on heap is final(doesn't makes sense at all, right?) instead what it means is that it variable will always point to the object to which it was initialized and nobody can change it.