Java Immutability – How to Create Immutable Methods

constfinalimmutabilityjava

In Java, there is the final keyword in lieu of the const keyword in C and C++.

In the latter languages there are mutable and immutable methods such as stated in the answer by Johannes Schaub – litb to the question How many and which are the uses of “const” in C++?

Use const to tell others methods won't change the logical state of this object.

struct SmartPtr {
    int getCopies() const { return mCopiesMade; }
}ptr1;

...

int var = ptr.getCopies(); // returns mCopiesMade and is specified that to not modify objects state.

How is this performed in Java?

Best Answer

You can't. I'm not familiar with Java 7, but at least in Java 6 you cannot tell the compiler a method is not supposed to mutate its arguments or the this instance.

Unfortunately final in Java doesn't mean the same as const in C++.

A final argument means something else: merely that you cannot reassign it, so that the following is an error:

A method(final B arg) {
    ...
    arg = something;  // error, since arg is final
    ...
}

This is a good practice, but it won't prevent you from mutating arg by calling one of its methods.

A final method such as final A method(...) is related to subclassing rules, and not with mutation.

Related Topic