Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "Mutable class" in OOP?

Tags:

oop

The standard class...is it mutable or not?

like image 503
TIMEX Avatar asked Aug 24 '10 07:08

TIMEX


People also ask

What is mutable and immutable class?

A mutable object can be changed after it's created, and an immutable object can't. In Java, everything (except for strings) is mutable by default: public class IntegerPair { int x; int y; IntegerPair(int x, int y) { this.

How do you know if a class is mutable?

To properly define mutable and immutable classes, one must first define what it means for an object instance to be mutable. An object instance is mutable if there is any possible(*) means via which the state encapsulated thereby might be modified. An object instance is immutable if its state cannot possibly be changed.

What is immutable object in OOP?

In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

What is immutable and mutable with example?

String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type. It has methods to delete parts of the string, insert or replace characters, etc.


2 Answers

It depends strongly on the language. Some of them do not even allow mutable objects.

Many mainstream languages default to being highly mutable, depending on what members you expose on your class's public interface. In at least a couple mainstream languages (particularly dynamic languages) it is really hard to make immutable objects.

See a definition of (im)mutable for more information:

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.

like image 66
Merlyn Morgan-Graham Avatar answered Jan 03 '23 16:01

Merlyn Morgan-Graham


A mutable class is one that can change its internal state after it is created.

Generally speaking, a class is mutable unless special effort is made to make it immutable.

like image 45
Bozho Avatar answered Jan 03 '23 16:01

Bozho