A class being Immutable means that the class state and/or value(s) cannot be changed after an instance of that class has been created. Making a class immutable can be accomplished in several ways; using final
variables can help, and making the class itself final
can help by preventing subclassing where the subclass could break the rules of immutability.
The use of the final
keyword on a class vs. using it on a variable mean two entirely different things.
Setting a class to be final means that class cannot be subclassed; that is, if you have
public final class X {...}
you can't extend it
public class Y extends X {...} // Illegal!
Whether or not a class is final has no bearing on the class member variables being final.
Setting a variable to be final
, whether it's a static
, a class member variable, or a local (to a method or a block) variable means that the variable can't be changed after it has been assigned a value.
Your code will also need to set a value to the final variable through any available execution path, so this is OK, because it always sets "max" to something:
...
final int max;
if (parameter) {
max = 100;
} else {
max = 1000;
}
but this will give you an error:
...
final int max;
if (parameter) {
max = 100;
}
because it sets "max" if "parameter" evaluates to true
but never sets "max" otherwise.
This will usually be done in a constructor for an immutable object:
public final class X
{
final int value;
public X(int v)
{
this.value = v; // Now that `value` has been set
// it can never be changed
}
}
Declaring a class as final
does not imply anything about its class members being final, so your question "why do I still have to say" is because those two uses of final
are unrelated.
Note that you can also declare a method to be final:
public final int getMax() {...}
This means that a subclass is not allowed to override this method with a new implementation. (final
on a method makes no sense if the class is already final
because there can't be any subclasses that attempt to override the method.)