Re: Usefulness of "final" (Was: Re: Inserting In a List)
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.
If is neither sufficient nor necessary to make them
immutable.
final is necessary. [...]
public class Immutable {
private int value;
public Immutable(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
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 = av;
}
@Override public int getValue()
{
return foo;
}
public void setValue(int av)
{
foo =av;
}
}
Now you can have code like this:
MutableImmutable mui = new MutableImmutable(0);
Immutable immu = mui;
System.out.println("Immutable value = " + immu.getValue());
mui.setValue(-1);
System.out.println("Immutable value = " + immu.getValue());
If the "mui" and "immu" code are in different parts of the application, e.g=
.., one is
inside a method called separately from the other, you can have mutable beha=
vior
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
mutate the behavior of its parent, and break immutability, which is not pos=
sible if
the parent class defines 'value' to be 'final'.
So while 'final' is not necessary for immutability, it sure does help.
--
Lew