X-Received: by 10.224.185.79 with SMTP id cn15mr2294128qab.4.1365039699268; Wed, 03 Apr 2013 18:41:39 -0700 (PDT) X-Received: by 10.49.61.234 with SMTP id t10mr419238qer.16.1365039699254; Wed, 03 Apr 2013 18:41:39 -0700 (PDT) Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!border3.nntp.dca.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!ca1no28412683qab.0!news-out.google.com!ef9ni1849qab.0!nntp.google.com!ca1no28412680qab.0!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail Newsgroups: comp.lang.java.programmer Date: Wed, 3 Apr 2013 18:41:39 -0700 (PDT) In-Reply-To: Complaints-To: groups-abuse@google.com Injection-Info: glegroupsg2000goo.googlegroups.com; posting-host=69.28.149.29; posting-account=CP-lKQoAAAAGtB5diOuGlDQk0jIwmH0T NNTP-Posting-Host: 69.28.149.29 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> User-Agent: G2/1.0 MIME-Version: 1.0 Message-ID: Subject: Re: Usefulness of "final" (Was: Re: Inserting In a List) From: Lew Injection-Date: Thu, 04 Apr 2013 01:41:39 +0000 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Lines: 73 Xref: csiph.com comp.lang.java.programmer:23270 Eric Sosman wrote: > markspace wrote: >> Arne Vajh=EF=BF=BDj wrote: >>> But now you raise the question, then final is only slightly >>> involved in immutability in Java. >=20 >>> If is neither sufficient nor necessary to make them >>> immutable. >=20 >> final is necessary. [...] >=20 > public class Immutable { > private int value; > public Immutable(int value) { > this.value =3D value; > } >=20 > public int getValue() { > return value; > } > } >=20 > Claim: Immutable is immutable, despite the lack of "final". 'final' can help in some superficially similar scenarios. public class MutableImmutable extends Immutable { private int foo; public MutableImmutable(int av) { super(av); foo =3D av; } @Override public int getValue() { return foo; } public void setValue(int av) { foo =3Dav; } } Now you can have code like this: MutableImmutable mui =3D new MutableImmutable(0); Immutable immu =3D mui; System.out.println("Immutable value =3D " + immu.getValue()); mui.setValue(-1); System.out.println("Immutable value =3D " + immu.getValue()); If the "mui" and "immu" code are in different parts of the application, e.g= ., one is=20 inside a method called separately from the other, you can have mutable beha= vior=20 from an 'Immutable' reference even though the parent class is actually immu= table. Furthermore, if 'Immutable#value' were not 'private', then the overriding c= lass can=20 mutate the behavior of its parent, and break immutability, which is not pos= sible if=20 the parent class defines 'value' to be 'final'. So while 'final' is not necessary for immutability, it sure does help. --=20 Lew