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?
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.
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