Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx05.eternal-september.org!.POSTED!not-for-mail From: markspace Newsgroups: comp.lang.java.programmer Subject: Re: Usefulness of "final" (Was: Re: Inserting In a List) Date: Wed, 03 Apr 2013 18:46:35 -0700 Organization: A noiseless patient Spider Lines: 49 Message-ID: References: <19un43xj77bua.vw45l4e2wshi.dlg@40tude.net> <515cabb2$0$32111$14726298@news.sunsite.dk> <515cc192$0$32109$14726298@news.sunsite.dk> <515cc3b2$0$32111$14726298@news.sunsite.dk> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 4 Apr 2013 01:44:12 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="fba3415ba68d85d643935af2f52f0b4b"; logging-data="6583"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/m72wj7yMqlJSTB1oc1EvcbKz06UPzgi8=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20130328 Thunderbird/17.0.5 In-Reply-To: Cancel-Lock: sha1:ucRfqAsY7wEgnkNpX6QWUa6Tg7w= Xref: csiph.com comp.lang.java.programmer:23271 On 4/3/2013 6:31 PM, Lew wrote: > markspace wrote: >> final is necessary. It is not sufficient (you also have to not mutate >> the object in question after the enclosing object's ctor exits). I'm >> pretty sure the field must also be explicitly private. (Implicitly > > Nope. > > You can have immutable public fields. > Well, that's true. I'm clearly getting a little sloppy in my language with all the different posts I've been making. A final field can be immutable and public if it's a primitive or if the object it references is immutable. I think that covers it. > public class ImmutableA > { > private final String ident = "Immutable instance"; > } > > Now 'ImmutableA' instances are immutable. Not only that, but in this case, because > 'ident' is 'final' and initialized by a constant expression, it is now a constant variable. > And because String itself is immutable. public class NotImmutable { public final char[] string = {'a','b','c'}; } final, public, initialized by a constant expression, but not immutable. This is also immutable: public class ImmutableB { public final String string = "abc"; } Can't change it, so it's OK to be public. Thread safe immutable. (See my post to Eric, what the JLS actually says in section 17.5 is "thread safe immutable", which is rather different from just "immutable." I've been confusing the two terms in my posts when I really should not. What I've really been talking about I should call "thread safe immutable" to match the JLS.)