Primitive type variables (int, long, short, etc.) can be reassigned after being defined. We can prevent this using final.
int i = 42; //int is of primitive type
i = 43; // OK
final int j = 42;
j = 43; // does not compile. j is final so can't be reassigned
Reference types cannot be made immutable just by using the final keyword. final only prevents reassignment.
final MyObject m = new MyObject(); //m is of reference type
m.data = 100; // OK. We can change state of object m (m is mutable and final doesn't change this fact)
m = new MyObject(); // does not compile. m is final so can't be reassigned
Benefits
https://www.linkedin.com/pulse/20140528113353-16837833-6-benefits-of-programming-with-immutable-objects-in-java
No comments:
Post a Comment