M
markspace
final Point p = new Point(0, 0);
p.move(1, 1);
Are you really trying to say that you believe that the final keyword has
made p immutable,
Nope, p is clearly mutable here.
public class A {
final int b = 123;
}
OK, as far as it goes. But see below.
But of course, again, you cannot make an mutable OBJECT immutable simply by
creating a reference to it that is decorated with final.
Yup, you can. This class is also immutable:
public class Stooges {
private final ArrayList<String> stooges = new ArrayList<>(3);
{ stooges.add("Larry"); stooges.add("Curly"); stooges.add("Moe");}
public String getStooge( int stooge ) {
if( stooge < 1 || stooge > 3 ) throw new IllegalArgumentException();
return stooges.get( stooge-1 );
}
}
Now as long as I haven't made some syntax or other simple error, all
instances of Stooges are immutable under the section of the JLS I
quoted. More over, each one is thread safe in all circumstances and
does not need synchronization to make it thread safe.
You may know this yourself, but the way you wrote the bit I quoted made
is sound like final fields have no special semantics associated with
them with respect to immutable objects (like the stooges ArrayList I
used above), when in fact they do. Although not in the fashion you
implied with p above, of course.
Again, I'm pretty certain that you already know all of the above and we are
just having a communication breakdown.
I think so.