Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between immutable and final

Tags:

groovy

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
}
like image 765
More Than Five Avatar asked Apr 16 '14 06:04

More Than Five


People also ask

What is the difference between immutable and final?

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.

Why string is immutable and final?

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.

What is the difference between immutable and constant?

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.

Does declaring an object final makes it immutable?

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.


1 Answers

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

like image 95
Russell Cohen Avatar answered Sep 18 '22 11:09

Russell Cohen