6

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
}

2 Answers 2

5

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

1
  • 1
    "The first class is equivalent to the second class with several helper functions" - this is an extremely vague description of the considerable differences between these two concepts
    – Dónal
    Apr 16, 2014 at 12:31
3

The @Immutable annoatation causes the compiler to transform a class such that it cannot be changed after construction. The final modifier - when applied to a variable/field - ensures that the variable cannot be reassigned after construction. When applied to a class, final prevents the class from being extended.

When a class is declared immutable, the types of all the properties must also be immutable, or the compiler must know how to make them immutable, which it does for Date, Collection, Map, etc. So in your example above MyOtherClass must also be immutable.

To illustrate the difference between a final field and an immutable field

class FinalClass {
    final List list
}

because list is final, you cannot reassign it after construction like this:

def fc = new FinalClass(list: [])
fc.list = [] // throws a ReadOnlyPropertyException

But you can mutate this field, e.g.

def fc = new FinalClass(list: [])
fc.list << new Object()

By contrast, a field of an immutable class can neither be reassigned nor mutated. For example, if FinalClass is annotated with @Immutable the following attempt to mutate a field would cause an exception to be thrown

def fc = new FinalClass(list: [])
fc.list << new Object()  // throws an UnsupportedOperationException

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.