1 of 2

Object oriented immutability: final classes or final methods

One of the things you see in numerous places in the standard java library is final classes. It is claimed that this is for immutability which I understand...to an extent.

Suppose you have a class:

final public class ImmutableTest {
    private String value;
    public ImmutableTest(String value) {
        this.value = value;
    }
    public String getValue() {
        return this.value;
    }
}

You can say that the value is immutable because it can't be adapted after creation. However this limits usability of the class as no one can extend it (for example to use as a drop-in for a bad interfaceless design...).

Now suppose you have this class:

public class ImmutableTest {
    private String value;
    public ImmutableTest(String value) {
        this.value = value;
    }
    final public String getValue() {
        return this.value;
    }
}

The "value" is still immutable but now at least people can extend the class. Someone once interjected: but if you extend it, the extended class is not guaranteed to be immutable!

While this is true, I think it is immaterial to the class itself.

If user A uses my ImmutableTest class everywhere in his code, he only has access to the "value" anyway which remains immutable. Unless he does explicit casting (in other words: he's aware that he's trying to access other stuff) he can't access a "mutable" part of the actual instance which means from the developer's point of view the class is as immutable as it should be, even if the actual instance has other mutable variables.

So in short: my opinion is that final classes are superfluous as final methods are all you need. I would love to hear arguments to the contrary though!