Reputation: 6892
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?
Upvotes: 5
Views: 1055
Reputation: 51363
Now he ask me there is a immutable class with only getter methods.
Then in this class what is the use of final?
Only getter methods do not ensure that a class is immutable. If you expose the internal state than a client can change the class's state.
Immutable means that you can not change an objects state once it is created.
Making all fields final and providing only getters will not make it immutable out of the box. Imagine the following code:
public class MyString {
private final char[] content;
public MyString(String str){
this.content = str.toCharArray();
}
public char[] getContent(){
return this.content; // internal state exposed. You should return a copy.
}
}
This class has only final fields and only getter methods but is still mutable. Imagine this client code:
MyString myString = new MyString("test");
myString.getContent()[0] = 'f';
Now he ask me there is a immutable class with only getter methods.
Then in this class what is the use of final?
The use of final is to express your intention with java's language features and therefore enforce them by the compiler.
So making a variable final is good for primitive types, but you must take care if the variable is a reference. In this case you must either ensure that
The later can only be ensured by the programmer. So take extra care when you return references.
Upvotes: 2
Reputation: 5622
Well, immutability is of course achieved in the way that an object is used, rather than by enforcement. You could always change a final field's value with Reflection.
The use of it is to allow the compiler to prevent you from breaking immutability, as well as to denote the need for immutability (such as when you use an inner class that uses a method-local reference).
Upvotes: 0
Reputation: 111
'final' as the keyword's name suggest means that the attribute to which final keyword is attached can't be changed(in terms of value) in other words it behaves like a constant.if fields are not 'final' then inside local method you can change the value of fields.
Upvotes: -1
Reputation: 2158
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.
Upvotes: 6