The standard class...is it mutable or not?
A mutable class is a class that has a changeable state.
for example, if you have a class representing a number, Number
, then it is mutable if you can do something like
Number num(4);
num.set(5);
i.e., change the internal state.
from Wikipedia:
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. An object can be either entirely immutable or some attributes in the object may be declared immutable; for example, using the const member data attribute in the C++ programming language.
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:
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.
Please refer to this :http://www.javaranch.com/journal/2003/04/immutable.htm Explains mutable and immutable ojects in java.
Being a class mutable or immutable depends on the logic you write.Now assume a person class with the following properties,
public class Person
{
public string Firstname{get;private set;};
private string Lastname{get;private set;};
public Person(string firstname,string lastname)
{
Firstname = firstname;
Lastname = lastname;
}
//Assume Person class contains no other methods or what so ever,now include this method,
//this method makes the Person Object mutable.Means you can change the state of it.
public void UpdateName1(string firstname,string lastname)
{
Firstname = Firstname+firstname;
Lastname = Lastname+lastname;
}
//Assume Person class contains no other methods or what so ever,now include this method,
//this method makes the Person Object immutable,when you change the state of the object ,
//you will be returned with a brand new object with the desired state.You can see this behaviour in
//string objects also, in java and C#.
public Person UpdateName2(string firstname,string lastname)
{
return new Person(this.Firstname+firstname,this.Lastname+lastname)
}
}
Person p = new Person("Srinivas","reddy");
p.UpdateName1(" "," Thatiparthy");
//this code gives the brand new object with the desied state
Person newObj = p.UpdateName2(" "," Thatiparthy");
Classes are typically not mutable (though some languages deviate from this). The objects that you create from classes, on the other hand, are often mutable if they include state and you do not take special care to prevent anyone from changing that state after object creation.