Hicham Moustaid
Hicham Moustaid

Reputation: 784

Final fields and Immutable Classes

According to this: A Strategy for Defining Immutable Objects

One of the conditions for a class to be immutable, is making all its fields final and private.

Why final??? The other conditions aren't sufficient?

Upvotes: 2

Views: 1025

Answers (4)

Nitin Dandriyal
Nitin Dandriyal

Reputation: 1607

Counter question "Why not final?".

final means for primitive types you'll not be able to change the value once assigned which is enough to make them Immmutable,

while for non-primitive types the reference can't be changed (1st step towards Immutability) once assigned and you need to do some more as mentioned in the link shared by you.

Upvotes: 1

Trace Moridin
Trace Moridin

Reputation: 47

Per the definition for an immutable object (courtesy of Wikipedia) "In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created."

Once an final object has been created it cannot be re-assigned. Without the final key work you could still change an object after it has been created.

See also final object in java

Upvotes: 1

dkatzel
dkatzel

Reputation: 31648

The key to the linked document is this quote

Not all classes documented as "immutable" follow these rules....However, such strategies require sophisticated analysis and are not for beginners.

This is a tutorial for beginners. It's easier to tell them "make everything private and final" then have to explain all the edge cases with how to properly handle mutable references and making sure not to let your references escape.

Upvotes: 0

Razib
Razib

Reputation: 11153

Without making the field final we can make an immutable class/object if other conditions are available.

But I think the final is useful while dealing with concurrency and synchronization.

Upvotes: 1

Related Questions