In object-oriented programming, an immutable object is an object whose properties cannot be changed after it has been created. Most objects, by contrast, are mutable objects, meaning that some or all of their properties can be freely changed after creation. A variety of computer languages have the ability to create immutable objects, including Java, C++, erlang, Tcl and scala.
An immutable object can be created in one of two ways: by creating a class that is by definition immutable or by explicitly declaring an otherwise mutable object to be immutable. The methodology for creating an immutable class varies depending on the computer language that is used. Regardless of the language, an immutable class must have no methods that can change its internal data and no way for methods to be changed — i.e. overridden or overloaded — in a way that would change its internal data. This is the more complicated of the two approaches. To create an immutable object from an otherwise mutable object, on the other hand, one can often apply a keyword to designate the object as immutable.
As an example, immutable object creation in Java relies heavily on the "final" keyword. A quick way to make a class immutable in Java is to declare the class, as well as all of its methods and data members, final. A similar strategy can also be used in C++ with the "const" keyword. These approaches, depending on the class content, might not be the best ones, however. In general, objects can usually be made immutable by careful maintenance of their internal data.
Making an immutable object using a keyword, as in the above example, is often much easier than writing an entire class to be immutable. Using this approach, however, has its dangers. When explicitly designating an immutable object in this manner, it is important for the programmer to be sure that all appropriate properties and data have been incorporated into the object first. Relying on an incomplete object might be dangerous, particularly if it is missing an essential piece of information.
If an object is mutable but requires immutable data to be created properly, the immutable data must be initialized before the mutable object can be made. Immutable objects are always immutable, whether they are data values or large objects, and must always be treated as such. In general, an immutable object cannot be made mutable after it has been created, although they might sometimes be copied as mutable objects. It usually can be assumed that an immutable object and any of its copies are also immutable, which can prevent data or memory problems.