Reputation: 695
I'm learning about defensive copying.....
I need to ensure that the instance variable a in the example below is immutable. I have no mutator methods in the class, I've forbidden my accessor method from being overridden, and a is private and final.
However, I'm unsure if when I call getA() I need to follow the first or second approach...
Because Strings are immutable, I think the first, but I would really appreciate clarification because immutability is so important and I'm worried about the implications if I get it wrong!
private final String a;
final String getA() {
return a;
}
or
final String getA() {
return new String(letter);
}
Upvotes: 2
Views: 71
Reputation: 3017
You have it correct. By the way, the final
modifier on the method only means that the method can't be overridden in any subclasses, it doesn't really have anything to do with the immutability of a
.
Upvotes: 3
Reputation: 2327
Since Strings are immutable, there is no need to create a defensive copy of them; it is impossible for them to be modified other than by being replaced entirely by another string. Therefore the first version is correct. In fact, since a
is a final
field of an immutable class, it is entirely impossible for a
to be modified by anyone, and therefore it would be safe to simply make it public
with no accessor at all: public final String a
.
Note however that it is entirely unnecessary to declare the method as final
: non-final
methods may be overridden by subclasses, which will change the behavior if the method is called, but overriding this method relating to a
does not give the subclass any more access to a
than it did before.
Upvotes: 3