Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a field `Final` in an Immutable class?

Recently I attended an interview.

I was asked how you can make a class Immutable.

I told him the answer.

But then he asked me why the fields are final?

I answered so that the user doesn't accidentally change the value of the field and it will give compiler error if he does so.

Now he ask me there is a immutable class with only getter methods.

Then in this class what is the use of final?

I was not able to answer. He told there is a reason behind that.

Can somebody explain?

like image 592
Thinker Avatar asked Mar 14 '14 10:03

Thinker


1 Answers

From Effective Java:

Make all fields final. This clearly expresses your intent in a manner that is enforced by the system. Also, it is necessary to ensure correct behavior if a reference to a newly created instance is passed from one thread to another without synchronization, as spelled out in the memory model.

like image 74
Jakub H Avatar answered Sep 30 '22 10:09

Jakub H