ImmutableRequiresFinalParametersDRAFT
For a class to be immutable,
all parameters of it’s constructors and methods need to be final
.
Immutable classes need final constructor/method parameters
Immutable classes can have constructor/method parameters that are not final
CorrectionHere is what's right.
Whether or not local variables and constructor and method parameters are final
has nothing to do with whether or not the class is immutable.
public class ImmutableCounter {
private final int count;
// parameter count is not final
public ImmutableCounter(int count) {
this.count = count;
}
public ImmutableCounter increment() {
return new ImmutableCounter(count + 1);
}
}
OriginWhere could this misconception come from?
This misconception may be related to the belief
that immutability is equivalent to using final
everywhere.
It may reflect a superficial understanding of immutability,
possibly originating in an instructors’ statement like
“to make a class immutable, make everything final”,
possibly combined with a confusion between shallow and deep immutability.