简体   繁体   中英

Strings and Immutability

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);

    }

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM