What is the difference between immutable and final?
For example, this
@Immutable
public MyClass {
String property1
MyOtherClass property2
List myLIst
}
and
public final MyClass {
final String property1
final MyOtherClass property2
final List myLIst
}
final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object's actual value can't be changed, but you can change its reference to another one.
The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. The reason of making string final is to destroy the immutability and to not allow others to extend it. The String objects are cached in the String pool, and it makes the String immutable.
The difference is that constant variables can never be changed after compilation, while immutable variables can be set within the constructor. From the docs: State variables can be declared as constant or immutable. In both cases, the variables cannot be modified after the contract has been constructed.
If we declare reference variable as final, it does not mean that the object is immutable in nature. In the next line of the code, we have called the append() method that successfully appends the string to the created object. If the object is immutable, the operation cannot perform.
The @Immutable annotation instructs the compiler to execute an AST transformation which adds the necessary getters, constructors, equals, hashCode and other helper methods that are typically written when creating immutable classes with the defined properties. [1]
So, @Immutable generates helper functionality, similar to "case classes" in Scala.
The final
keyword instructs the compiler that the particular variable is immutable, as it means in Java.
The first class is equivalent to the second class with several helper functions.
[1] http://groovy.codehaus.org/gapi/groovy/transform/Immutable.html
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