What do unchangeable objects mean

What does 'immutable' mean?

Immutable means unchangeable in German. If an object is immutable in Java, it is not modifiable. More or less at least.

This article should clarify what that means exactly.

Table of Contents

Imutablity through

The keyword changes variables in such a way that they can only be assigned once. does not make an object immutable, but a variable "can no longer be reassigned". The method defines constants in Java:

If variables of primitive data types or immutable types are declared as final from the start, these can no longer be changed.

Imutability of objects

Objects are then considered immutable, i.e. unchangeable, if all fields can only be accessed for reading. An example is the class that has already been used here several times:

Objects of the class cannot be changed because the individual fields can only be accessed for reading. However, the class allows it to be inherited, which means that the getters can be overwritten and setters can be added.

Thus, variables of the type can be assigned to mutable objects of the type, although one would assume that objects are immutable:

One way to prevent this from happening is to do the class yourself. as a result, derivations by other classes are no longer permitted. The following cannot be inherited from a class:

Attempting to inherit from this class would result in a compiler error.

The problem with mutable properties

If individual fields or properties are of a mutable, i.e. mutable, type, the object as a whole is again not immutable.


Similar articles